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 }