在WCF REST 4.0中使用StandardEndpoints时如何配置MessageInspector [英] How do you configure a MessageInspector when using StandardEndpoints in WCF REST 4.0

查看:89
本文介绍了在WCF REST 4.0中使用StandardEndpoints时如何配置MessageInspector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建和配置消息检查器以对WCF Rest HTTP请求执行一些身份验证.我正在使用4.0,因此尽管我设法以我想要的方式使旧的RequestInterceptor正常运行,但试图避开WCF入门工具包.使用RequestInterceptor的问题是我丢失了WebHttpBehavior提供的autoFormatFormationionEnabled功能,而我确实希望保留这些功能.

I'm trying create and configure a Message Inspector to perform some authentication of a WCF Rest HTTP request. I'm using 4.0 so trying to steer clear of the WCF Starter Kit although I have managed to get an old RequestInterceptor working in the way I want. The problem with using RequestInterceptor is that I lost the automaticFormatSelectionEnabled features provided by WebHttpBehavior which I really want to keep.

所以我的问题是如何以仍然使用WebHttpBehavior并保留其功能的方式配置消息检查器.

So my question is how do I configure the Message Inspector in a way that I still use the WebHttpBehavior and keep it's features.

我的web.config看起来像这样

My web.config looks like this

    <standardEndpoints>
  <webHttpEndpoint>
    <!-- the "" standard endpoint is used by WebServiceHost for auto creating a web endpoint. -->
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
    <!-- Disable the help page for the directory end point-->
    <standardEndpoint name="DirectoryEndpoint"/>
  </webHttpEndpoint>
</standardEndpoints>

推荐答案

处理此问题的一种方法是创建三个对象.

One way you can handle this is to create three objects.

  1. 邮件检查器,负责分析 请求/响应
  2. 服务行为会自动将检查器注入到 管道
  3. 配置部分,允许在 web.config
  1. The message inspector, responsible for analyzing the request/response
  2. The service behavior, automatically injects the inspector into the pipeline
  3. The configuration section, allows the behavior to be used in the web.config

首先通过实现IDispatchMessageInspector创建消息检查器 并将验证代码放入AfterReceiveRequest方法中:

First create the message inspector by implementing IDispatchMessageInspector and putting your validation code in the AfterReceiveRequest method:

public class HmacVerificationInspector : IDispatchMessageInspector
{

    #region IDispatchMessageInspector Members

    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, 
        System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            Message dupeRequest = buffer.CreateMessage();

            ValidateHmac(dupeRequest);

            buffer.Close();

        return null;
    }

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, 
        object correlationState)
    {


    }

    #endregion
}

读取消息时创建消息的缓冲副本很重要.消息只能打开一次,并且不能创建副本将导致问题.如果失败,我的ValidateHmac实现将引发异常.这样可以防止实际的服务被调用.

It's important to create a buffered copy of the message when reading it. Messages can only be opened once and not creating a copy will lead to problems down the pipe. My implementation of ValidateHmac throws an exception if it fails. This prevents the actual service from being called.

第二,为检查员创建一个行为.我们将使用该行为将检查器注入WCF运行时.要创建行为,请从IEndpointBehavior派生一个类,使它看起来像这样

Second, create a behavior for your inspector. We'll use the behavior to inject the inspector into the WCF runtime. To create the behavior, derive a class from IEndpointBehavior so it looks like this

 public class HmacVerificationBehavior : IEndpointBehavior
    {
        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {

        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            HmacVerificationInspector inspector = new HmacVerificationInspector();

            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
        }

        public void Validate(ServiceEndpoint endpoint)
        {

        }

        #endregion
    }

注意,我创建了检查器(HmacVerificationInspector)的新实例,并以编程方式将其注入运行时.

Notice I create a new instance of my inspector (HmacVerificationInspector) and inject it programmatically into the runtime.

最后,最后一步是创建配置部分.我们可以使用它在Web配置中应用行为(因此可以通过配置打开和关闭它).创建一个新类并从BehaviorExtensionElement和IServiceBehavior继承:

Finally, the last step is to create a configuration section. We can use this to apply the behavior in the web config (thus being able to turn it on and off via configuration). Create a new class and inherit from BehaviorExtensionElement and IServiceBehavior:

public class HmacVerificationConfigurationSection : BehaviorExtensionElement, IServiceBehavior
{
    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, 
        System.ServiceModel.ServiceHostBase serviceHostBase, 
        System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
        System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {

    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {

    }

    #endregion

    public override Type BehaviorType
    {
        get { return typeof(HmacVerificationBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new HmacVerificationBehavior();
    }
}

现在,要使用检查器,请将以下内容添加到web.config中(您可以将扩展名设置为所需的名称)

Now, to use the inspector, add the following to your web.config (you can set the name for your extension to whatever you want)

<system.serviceModel>
        <extensions>
            <behaviorExtensions>
                <add name="hmacVerification" type="NamespaceHere.HmacVerificationConfigurationSection, AssembleyHere, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            </behaviorExtensions>
        </extensions>
        <services>
            <service name="MySecureService">
                <endpoint address="" binding="webHttpBinding" contract="IMySecureService" behaviorConfiguration="web" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="web">
                    <webHttp automaticFormatSelectionEnabled="true" />          
                    <hmacVerification />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    </system.serviceModel>

事物的结合,首先您在行为扩展中注册配置部分.接下来,您将该配置用作端点行为,然后将自动注入检查器,并且对该端点的所有请求都将通过您的检查器运行.如果要关闭检查器,请删除标签或选择其他端点行为.注意还要使用webHttp行为(这将使您保持automaticFormatSelectionEnabled.

Couple of things, first you register the configuration section in the behavior extensions. Next, you use that configuration as an endpoint behavior which will then automatically inject the inspector and all requests to that endpoint will run through your inspector. If you want to turn off the inspector, remove the tag or select a different endpoint behavior. Note the use of the webHttp behavior also (which will allow you to keep automaticFormatSelectionEnabled.

希望这会有所帮助

这篇关于在WCF REST 4.0中使用StandardEndpoints时如何配置MessageInspector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆