如何限制特定ip的wcf服务方法

ibu*_*ubi 1 c# wcf

这是我的 wcf 服务方法:

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

如果我的方法从http://particularIP.com调用/调用,我希望我的方法发送响应正常,除非响应错误请求。

我怎样才能做到这一点?

Ana*_*tix 5

您可以在 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>
Run Code Online (Sandbox Code Playgroud)

已编辑

或者使用可以从 OperationContext 获取客户端 IP 的 ServiceAuthorizationManager.CheckAccessCore。

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;
Run Code Online (Sandbox Code Playgroud)