2012-01-27 11 views

答えて

10

ユーザーの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()を使用する方が適しています。

+0

"このコンテキストではリクエストは利用できません" – oneNiceFriend

1

コントローラのパラメータで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(); 
関連する問題