2016-12-14 52 views
0

這裏是我的WCF服務的方法:如何限制WCF服務方法爲特定的IP

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/CheckID/{id}")] 
    public string CheckID(string id) 
    { 
      /*Check reuqest where it comes from */ 
    } 

我希望我的方法來發送響應OK如果它是從http://particularIP.com調用,除非響應錯誤請求/。

我該怎麼做?

回答

3

可以在web.config文件中使用IP篩選器,如: -

<serviceBehaviors> 
    <behavior name="ServiceBehaviour"> 
     <serviceMetadata httpGetEnabled="true" /> 
     <serviceDebug includeExceptionDetailInFaults="true" /> 
    </behavior> 
    <behavior name="RestrictedServiceBehaviour"> 
     <serviceMetadata httpGetEnabled="true" /> 
     <serviceDebug includeExceptionDetailInFaults="true" /> 
     <IPFilter filter="172.*.*.* 127.0.0.1" />   
    </behavior> 
    </serviceBehaviors> 

編輯

或者使用可以在ServiceAuthorizationManager.CheckAccessCore你從的OperationContext獲取客戶端IP。

https://msdn.microsoft.com/en-us/library/system.servicemodel.serviceauthorizationmanager.checkaccesscore.aspx

編輯2

using System.ServiceModel; 
using System.ServiceModel.Channels; 

OperationContext context = OperationContext.Current; 
MessageProperties prop = context.IncomingMessageProperties; 
RemoteEndpointMessageProperty endpoint = 
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
string ip = endpoint.Address; 
+0

我不知道如何使用CheckAccessCore方法,似乎應該overrided但doesnt't出現在我的項目。 – ibubi

+0

您需要在應用程序中包含「System.ServiceModel」dll。 –

+0

謝謝Anand,我可以在不執行CheckAccessCore方法的情況下獲得OperationContext。但是,這是一個非常複雜的對象,clint ip數據被保存在哪裏? – ibubi