2010-08-28 46 views
21

嘿,你怎麼弄的人的IP地址發出請求在類似如下:WCF 4 Rest獲取請求IP?

[ServiceContract]  
    [AspNetCompatibilityRequirements(RequirementsMode = 
    AspNetCompatibilityRequirementsMode.Required)]  
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]   
    public partial class UsersService 
    {       
     [WebInvoke(UriTemplate = "", Method = "PUT")]   
     public User AddNewUser(User newUser) 
     {    
      // code goes here including GETTING AN IP?? 
     } 

謝謝!

回答

38

內AddNewUser函數使用下面的代碼片段:

OperationContext context = OperationContext.Current; 
MessageProperties messageProperties = context.IncomingMessageProperties; 
RemoteEndpointMessageProperty endpointProperty = 
    messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 

RemoteEndpointMessageProperty實例提供地址和端口屬性。

+1

問題是,除非在.Net 4中發生了一些變化,否則在使用WebHttpBinding時獲取OperationContext是一件非常痛苦的事情。我可以通過創建MessageInspector來完成,但它需要退出一些箍跳。 – 2010-08-28 12:42:56

+0

我不確定你是什麼意思。 OperationContext必須在任何WCF調用中可用,即使它是WebHttpBinding上公開的REST服務。我在WCF 4中測試過它,它可以工作。 – 2010-08-28 12:58:06

+0

在帶有WebHttpBinding的.Net 3.5中,您可以訪問WebOperationContext,但OperationContext不可直接使用。我很高興聽到他們在4.0版本中修復了這個問題。 – 2010-08-29 17:55:38