2012-01-27 49 views

Trả lời

10

Bạn có thể lấy địa chỉ IP của người dùng trong một lớp tĩnh như sau:

 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; 

Kỹ thuật này là tốt hơn để sử dụng Request.UserHostAddress() vì đôi khi sẽ chỉ ghi lại địa chỉ IP của proxy của người dùng.

+0

Điều này khiến "Yêu cầu không có sẵn trong lỗi ngữ cảnh này" – oneNiceFriend

1

bạn có thể vượt qua HttpContext.Current theo tham số của bộ điều khiển để StaticClass nhưng là một thực hành xấu.

Thực tiễn tốt nhất là trong hàm tạo của Bộ điều khiển nhận giao diện của lớp thực hiện.

private readonly IService _service; 

     public HomeController(IService service) 
     { 
      _service = service; 
     } 

và trong lớp học Dịch vụ

private readonly HttpContextBase _httpContext; 
    public Service (HttpContextBase httpContext) 
     { 
      _httpContext= httpContext; 
     } 

sau đó sử dụng IOC Containner (Ninject, AutoFac vv) cho dependences quyết

dụ trong AutoFac (global.asax)

builder.RegisterControllers(typeof(MvcApplication).Assembly); 
builder.RegisterModule(new AutofacWebTypesModule()); 
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope(); 
Các vấn đề liên quan