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

时间:2016-12-14 07:00:11

标签: 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 */
    }

我希望我的方法发送响应好,如果来自http://particularIP.com,则除非响应错误请求。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您可以在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>

<强>被修改

或者使用可以从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;