获取WCF的客户端IP地址,后期操作

Way*_* Lo 12 wcf client ip-address webinvoke

我试图通过以下链接确定客户端的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);
>     } } 
Run Code Online (Sandbox Code Playgroud)

注意事项:

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

我有WebInvoke/Post和WebGet的operationContracts.当客户端请求是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();
    ...
} 
Run Code Online (Sandbox Code Playgroud)

Pie*_*ick -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);
            }
Run Code Online (Sandbox Code Playgroud)