2016-12-14 59 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