[英]Get the IP address of the client connecting to a C# .NET WebAPI application
I tried: 我试过了:
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
according to: 根据:
Retrieving the client's IP address in ASP.Net Web API 在ASP.Net Web API中检索客户端的IP地址
this is the combined approach which should be valid for self host and webapi host. 这是对自我托管和webapi托管有效的组合方法。 Unfortunately I get null
instead of the IP address. 不幸的是,我得到的不是IP地址,而是null
。
I'm trying locally so I'd expect 127.0.0.1
or localhost
as the IP address 我正在本地尝试,所以我希望将127.0.0.1
或localhost
作为IP地址
Here is an expanded version of what you have that works for me. 这是对我有用的扩展版本。
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 GetClientIpString(this HttpRequestMessage request) {
//Web-hosting
if (request.Properties.ContainsKey(HttpContext)) {
dynamic ctx = request.Properties[HttpContext];
if (ctx != null) {
return ctx.Request.UserHostAddress;
}
}
//Self-hosting
if (request.Properties.ContainsKey(RemoteEndpointMessage)) {
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null) {
return remoteEndpoint.Address;
}
}
//Owin-hosting
if (request.Properties.ContainsKey(OwinContext)) {
dynamic ctx = request.Properties[OwinContext];
if (ctx != null) {
return ctx.Request.RemoteIpAddress;
}
}
if (System.Web.HttpContext.Current != null) {
return System.Web.HttpContext.Current.Request.UserHostAddress;
}
// Always return all zeroes for any failure
return "0.0.0.0";
}
public static IPAddress GetClientIpAddress(this HttpRequestMessage request) {
var ipString = request.GetClientIpString();
IPAddress ipAddress = new IPAddress(0);
if (IPAddress.TryParse(ipString, out ipAddress)) {
return ipAddress;
}
return ipAddress;
}
}
Assuming you are in a controller the above extension method allows for calls like: 假设您在控制器中,则上述扩展方法允许进行如下调用:
HttpRequestMessage request = this.Request;
var ip = request.GetClientIpString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.