gpt4 book ai didi

c# - 获取连接到 C# .NET WebAPI 应用程序的客户端的 IP 地址

转载 作者:太空狗 更新时间:2023-10-30 00:10:01 26 4
gpt4 key购买 nike

我试过:

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

根据:

Retrieving the client's IP address in ASP.Net Web API

这是对自托管和 webapi 托管有效的组合方法。不幸的是,我得到的是 null 而不是 IP 地址。

我在本地尝试,所以我希望 127.0.0.1localhost 作为 IP 地址

最佳答案

这是对我有用的扩展版本。

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

}

假设你在一个 Controller 中,上面的扩展方法允许这样的调用:

HttpRequestMessage request = this.Request;

var ip = request.GetClientIpString();

关于c# - 获取连接到 C# .NET WebAPI 应用程序的客户端的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com