12

我正在尝试通过以下链接确定客户端的 IP 地址:http ://www.danrigsby.com/blog/index.php/2008/05/21/get-the-clients-address-in-wcf/

在 .Net 3.0 中,没有可靠的方法来获取连接到 WCF 服务的客户端地址。在 .Net 3.5 中引入了一个名为 RemoteEndpointMessageProperty 的新属性。此属性为您提供客户端连接进入服务的 IP 地址和端口。获取这些信息非常简单。只需通过 RemoteEndpointMessageProperty.Name 从当前 OperationContext 的 IncomingMessageProperties 中拉出它并访问 Address 和 Port 属性。

> [ServiceContract] public interface IMyService {
>     [OperationContract]
>     string GetAddressAsString(); }
> 
> public class MyService : IMyService {
>     public string GetAddressAsString()
>     {
>         RemoteEndpointMessageProperty clientEndpoint =
>             OperationContext.Current.IncomingMessageProperties[
>             RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
> 
>         return String.Format(
>             "{0}:{1}",
>             clientEndpoint.Address, clientEndpoint.Port);
>     } } 

注意事项:

  1. 此属性仅适用于 http 和 tcp 传输。在所有其他传输(例如 MSMQ 和 NamedPipes)上,此属性将不可用。
  2. 地址和端口由服务机器的套接字或 http.sys 报告。因此,如果客户端通过 VPN 或其他修改地址的代理进入,则将表示新地址,而不是客户端的本地地址。这是可取且重要的,因为这是服务将客户端视为的地址和端口,而不是客户端将自身视为的地址和端口。这也意味着可能存在一些欺骗行为。客户端或客户端和服务器之间的某些东西可能会欺骗地址。因此,除非您添加一些其他自定义检查机制,否则不要将地址或端口用于任何安全决策。
  3. 如果您在服务上使用双工,那么不仅服务会为客户端填充此属性,而且客户端还会为来自该服务的每个调用填充此属性。

我有 WebInvoke/Post 和 WebGet 的操作合同。当客户端请求是 WebGet 时,该代码有效。但是当客户端请求是 WebInvoke 时,我会得到 WCF 主机 IP。有什么解决办法吗?谢谢。

这是界面

[OperationContract]
[WebGet(UriTemplate = RestTemplate.hello_get)]
Stream hello_get();

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = RestTemplate.hello_post)]
Stream hello_post();

// Code for getting IP
private string getClientIP()
{
    //WebOperationContext webContext = WebOperationContext.Current;

    OperationContext context = OperationContext.Current;

    MessageProperties messageProperties = context.IncomingMessageProperties;

    RemoteEndpointMessageProperty endpointProperty =

    messageProperties[RemoteEndpointMessageProperty.Name]

    as RemoteEndpointMessageProperty;
    return endpointProperty.Address;
}

public Stream hello_get()
{
    string ip = getClientIP();
    ...
}

public Stream hello_post()
{
    string ip = getClientIP();
    ...
} 
4

1 回答 1

-1

您是否尝试过使用 HttpContext?它并非在所有 WCF 模式下都可用,但这可能取决于您的环境:

if (HttpContext.Current != null)
            {
                Trace.WriteLine(
                    "Who's calling? IP address: '{0}', Name: '{1}', User Agent: '{2}', URL: '{3}'.",
                    HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.UserHostName,
                    HttpContext.Current.Request.UserAgent, HttpContext.Current.Request.Url);
            }
于 2014-08-17T19:07:55.237 回答