gpt4 book ai didi

c# - 在负载平衡情况下使用 WCF 4.5 RemoteEndpointMessageProperty 获取客户端 IP 地址

转载 作者:太空狗 更新时间:2023-10-29 22:07:10 28 4
gpt4 key购买 nike

我在 IIS 中托管了 WCF 4.5 Restful 服务,我正在尝试使用RemoteEndpointMessageProperty 获取客户端的 IP 地址使用服务。

代码 1:

private string GetClientIP()
{
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;
return ip;
}

代码 2:

private string GetClientIP()
{
string retIp = string.Empty;
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
HttpRequestMessageProperty endpointLoadBalancer =
prop[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (endpointLoadBalancer.Headers["X-Forwarded-For"] != null)
{
retIp = endpointLoadBalancer.Headers["X-Forwarded-For"];
}
if (string.IsNullOrEmpty(retIp))
{
RemoteEndpointMessageProperty endpoint =
prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
retIp = endpoint.Address;
}
return retIp;
}

但是,由于 WCF 服务托管在负载均衡器后面的 IIS 中,因此我得到的 IP 地址始终是负载均衡器的 IP。有什么办法可以解决这个问题,这样我就可以获得真实的 IP客户?

最佳答案

OperationContext context = OperationContext.Current;
MessageProperties properties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string address = string.Empty;
//http://www.simosh.com/article/ddbggghj-get-client-ip-address-using-wcf-4-5-remoteendpointmessageproperty-in-load-balanc.html
if (properties.Keys.Contains(HttpRequestMessageProperty.Name))
{
HttpRequestMessageProperty endpointLoadBalancer = properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (endpointLoadBalancer != null && endpointLoadBalancer.Headers["X-Forwarded-For"] != null)
address = endpointLoadBalancer.Headers["X-Forwarded-For"];
}
if (string.IsNullOrEmpty(address))
{
address = endpoint.Address;
}

这适用于负载均衡器的情况,也适用于没有负载均衡器的情况。我有一个端点作为 TCP,另一个端点作为 REST API 的 Web http。

关于c# - 在负载平衡情况下使用 WCF 4.5 RemoteEndpointMessageProperty 获取客户端 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166679/

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