你的位置:首页 > ASP.net教程

[ASP.net教程].NET 客户IP地址捕捉


MVC模式下要获取客户IP可以在ActionFilterAttribute中进行拦截

1 filterContext.HttpContext.Request.UserHostAddress

同样,在WebAPI中也可以用同样的方式获取,只是继承自System.Web.Http.Filters.ActionFilterAttribute

 1 private string GetClientIP(HttpActionContext actionContext) 2     { 3       if (actionContext.Request.Properties.ContainsKey("MS_HttpContext")) 4       { 5         return ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress; 6       } 7  8       if (actionContext.Request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) 9       {10         RemoteEndpointMessageProperty prop;11         prop = (RemoteEndpointMessageProperty)actionContext.Request.Properties[RemoteEndpointMessageProperty.Name];12         return prop.Address;13       }14 15       return null;16     }