static class
のクライアントのIPアドレスを取得したいです。asp.net mvcで静的クラスのクライアントIPアドレスを取得する方法
しかし、静的クラスのリクエストオブジェクトにアクセスできません。
静的クラスのリクエストオブジェクトなしでIPアドレスを取得する方法はありますか?
static class
のクライアントのIPアドレスを取得したいです。asp.net mvcで静的クラスのクライアントIPアドレスを取得する方法
しかし、静的クラスのリクエストオブジェクトにアクセスできません。
静的クラスのリクエストオブジェクトなしでIPアドレスを取得する方法はありますか?
ユーザーのIPアドレスは、次のような静的なクラスで取得できます。
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
このテクニックは、ユーザーのプロキシのIPアドレスだけを取得するため、このRequest.UserHostAddress()を使用する方が適しています。
コントローラのパラメータでHttpContext.CurrentをStaticClassに渡すことはできますが、悪い習慣です。
ベストプラクティスは、コントローラのコンストラクタにあり、実装クラスのインターフェイスを取得します。
private readonly IService _service;
public HomeController(IService service)
{
_service = service;
}
およびサービス・クラスで
private readonly HttpContextBase _httpContext;
public Service (HttpContextBase httpContext)
{
_httpContext= httpContext;
}
その後、解決依存性のためにIOC Containner(Ninject、AutoFacなど)を使用
AutoFac(Global.asaxの)中exemple
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();
"このコンテキストではリクエストは利用できません" – oneNiceFriend