2013-04-26 155 views
4

我有一个WCF REST休息服务,由Windows服务托管。它使用自定义的UserNamePasswordValidator身份验证。UserNamePasswordValidator中的客户端IP地址

我想获得客户端的IP地址进行验证时:

ublic static string GetClientIPAddress() 
    { 
     try 
     { 
      var context = OperationContext.Current; 
      var prop = context.IncomingMessageProperties; 
      var endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
      return endpoint.Address; 
     } 
     catch (System.Exception exc) 
     { 
      Debug.Assert(false,exc.Message); 
      return string.Empty; 
     } 
    } 

但它抛出一个异常,因为背景是在这种情况下空。我该如何解决这个问题?请注意,大多数建议的asp.net兼容模式不是一种选择,我的服务由WIndows服务托管,而不是由IIS托管。

谢谢!

+0

为什么你不使用IIS? – Mingebag 2013-04-26 13:53:36

+0

因为我必须将它安装到更多的机器,其中IIS没有使用 – Tom 2013-04-26 18:32:15

+0

但是如果你正在制作一个.net应用程序,你就把它放到了应用程序中。在服务器上,并安装在那里IIS,多数民众赞成在它,所以你不需要在每个客户端上安装它.. – Mingebag 2013-04-27 10:17:13

回答

1

Heey尝试应该工作的解决方案。

private string GetClientIp(HttpRequestMessage request) 
{ 
    if (request.Properties.ContainsKey("MS_HttpContext")) 
    { 
     return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; 
    } 
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) 
    { 
     RemoteEndpointMessageProperty prop; 
     prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name]; 
     return prop.Address; 
    } 
    else 
    { 
     return null; 
    } 
} 
+1

如果没有上下文可用,“HttpRequestMessage”来自哪里? – 2014-08-13 20:14:07

+0

使用私有方法发布答案时没有上下文调用的上下文没有帮助。 – 2016-03-22 19:55:22