.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         }

 

posted @ 2016-11-18 11:13  追寻未来的笨鸟  阅读(671)  评论(0编辑  收藏  举报