首页 > 代码库 > webapi获取IP的方式
webapi获取IP的方式
using System.Net.Http;public static class HttpRequestMessageExtensions{ private const string HttpContext = "MS_HttpContext"; private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; private const string OwinContext = "MS_OwinContext"; public static string GetClientIpAddress(this HttpRequestMessage request) { // Web-hosting. Needs reference to System.Web.dll if (request.Properties.ContainsKey(HttpContext)) { dynamic ctx = request.Properties[HttpContext]; if (ctx != null) { return ctx.Request.UserHostAddress; } } // Self-hosting. Needs reference to System.ServiceModel.dll. if (request.Properties.ContainsKey(RemoteEndpointMessage)) { dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage]; if (remoteEndpoint != null) { return remoteEndpoint.Address; } } // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll. if (request.Properties.ContainsKey(OwinContext)) { dynamic owinContext = request.Properties[OwinContext]; if (owinContext != null) { return owinContext.Request.RemoteIpAddress; } } return null; }}
References required:
HttpContextWrapper
- System.Web.dllRemoteEndpointMessageProperty
- System.ServiceModel.dllOwinContext
- Microsoft.Owin.dll (you will have it already if you use Owin package)
第二种:
((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
webapi获取IP的方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。