问题 如何在WCF服务中使用IDispatchMessageInspector?


我正在尝试使用 IDispatchMessageInspector 在WCF服务实现中访问自定义标头值。

就像是:

public class MyService : IMyService
{
    public List<string> GetNames()
    {
        var headerInspector = new CustomHeaderInspector();

        // Where do request & client channel come from?
        var values = headerInspector.AfterReceiveRequest(ref request, clientChannel, OperationContext.Current.InstanceContext);            
    }
}

我已经实现了自己的IDispatchMessageInspector类。

public class CustomHeaderInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        var userName = prop.Headers["Username"];

        return userName;
    }
}

我怎么通过

  • System.ServiceModel.Channels。信息 和

  • System.ServiceModel。IClientChannel

AfterReceiveRequest 叫 从服务实施?

编辑:

很多文章都喜欢 这个 要么 这个,举例说明如何实现自己的 ServiceBehavior。所以你的服务实现如下:

[MyCustomBehavior]
public class MyService : IMyService
{
    public List<string> GetNames()
    {
        // Can you use 'MyCustomBehavior' here to access the header properties?
    }
}

因此,我可以访问 MyCustomBehavior 以某种方式在服务操作方法中访问自定义标头值?


12294
2018-06-13 21:03


起源

blogs.msdn.com/b/zelmalki/archive/2008/12/29/...这可能会非常有帮助 - Sukhdev Zala


答案:


你必须配置

<extensions>
  <behaviorExtensions>
    <add 
      name="serviceInterceptors" 
      type="CustomHeaderInspector , MyDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
    />
  </behaviorExtensions>
</extensions>

然后,扩展将在您的WCF堆栈中处理。服务本身没有概念 serviceInterceptors 而且您不必在第一个代码块中执行某些操作。 WCF堆栈将为您注入Inspector。

MSDN:system.servicemodel.dispatcher.idispatchmessageinspector


6
2018-06-16 13:59



您对实施IDispatchmessageInspector的位置有任何了解吗?我开始另一个问题: stackoverflow.com/questions/31171943/... - Popo


我正在使用IClientMessageInspector达到同样的目标。 以下是如何从代码中应用它们:

 var serviceClient = new ServiceClientClass(binding, endpointAddress);
serviceClient.Endpoint.Behaviors.Add(
            new MessageInspectorEndpointBehavior<YourMessageInspectorType>());


/// <summary>
/// Represents a run-time behavior extension for a client endpoint.
/// </summary>
public class MessageInspectorEndpointBehavior<T> : IEndpointBehavior
    where T: IClientMessageInspector, new()
{
    /// <summary>
    /// Implements a modification or extension of the client across an endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint that is to be customized.</param>
    /// <param name="clientRuntime">The client runtime to be customized.</param>
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new T());
    }

    /// <summary>
    /// Implement to pass data at runtime to bindings to support custom behavior.
    /// </summary>
    /// <param name="endpoint">The endpoint to modify.</param>
    /// <param name="bindingParameters">The objects that binding elements require to support the behavior.</param>
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
        // Nothing special here
    }

    /// <summary>
    /// Implements a modification or extension of the service across an endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint that exposes the contract.</param>
    /// <param name="endpointDispatcher">The endpoint dispatcher to be modified or extended.</param>
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        // Nothing special here
    }

    /// <summary>
    /// Implement to confirm that the endpoint meets some intended criteria.
    /// </summary>
    /// <param name="endpoint">The endpoint to validate.</param>
    public void Validate(ServiceEndpoint endpoint)
    {
        // Nothing special here
    }
}

这里是MessageInspector的示例实现,我用它将客户端版本传递给服务器,并在自定义头文件中检索服务器版本:

/// <summary>
/// Represents a message inspector object that can be added to the <c>MessageInspectors</c> collection to view or modify messages.
/// </summary>
public class VersionCheckMessageInspector : IClientMessageInspector
{
    /// <summary>
    /// Enables inspection or modification of a message before a request message is sent to a service.
    /// </summary>
    /// <param name="request">The message to be sent to the service.</param>
    /// <param name="channel">The WCF client object channel.</param>
    /// <returns>
    /// The object that is returned as the <paramref name="correlationState " /> argument of
    /// the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)" /> method.
    /// This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid" /> to ensure that no two
    /// <paramref name="correlationState" /> objects are the same.
    /// </returns>
    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        request.Headers.Add(new VersionMessageHeader());
        return null;
    }

    /// <summary>
    /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
    /// </summary>
    /// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
    /// <param name="correlationState">Correlation state data.</param>
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        var serverVersion = string.Empty;
        var idx = reply.Headers.FindHeader(VersionMessageHeader.HeaderName, VersionMessageHeader.HeaderNamespace);
        if (idx >= 0)
        {
            var versionReader = reply.Headers.GetReaderAtHeader(idx);
            while (versionReader.Name != "ServerVersion"
                   && versionReader.Read())
            {
                serverVersion = versionReader.ReadInnerXml();
                break;
            }
        }

        ValidateServerVersion(serverVersion);
    }

    private static void ValidateServerVersion(string serverVersion)
    {
        // TODO...
    }
}

public class VersionMessageHeader : MessageHeader
{
    public const string HeaderName = "VersionSoapHeader";
    public const string HeaderNamespace = "<your namespace>";
    private const string VersionElementName = "ClientVersion";

    public override string Name
    {
        get { return HeaderName; }
    }

    public override string Namespace
    {
        get { return HeaderNamespace; }
    }

    protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
    {
        writer.WriteElementString(
            VersionElementName,
            Assembly.GetExecutingAssembly().GetName().Version.ToString());
    }
}

5
2018-06-17 12:42





我相信你不需要实现自定义 IDispatchMessageInspector 要检索自定义标头,可以从服务操作方法完成,如下所示:

var mp = OperationContext.Current.IncomingMessageProperties;
var property = (HttpRequestMessageProperty)mp[HttpRequestMessageProperty.Name];
var userName = property.Headers["Username"];

如果要中止消息处理,则实现自定义调度消息检查器是有意义的,例如,如果缺少凭据 - 在这种情况下您可以抛出FaultException。

但是,如果您仍想将值从调度消息检查器传递到服务操作方法 - 可能它可以通过一些单例与调用标识符(会话ID)一起传递,稍后通过方法提取,或者使用 wcf扩展


1
2018-06-19 20:56





我做了什么来访问细节我在里面设置了以下内容 IDispatchMessageInspector.AfterReceiveRequest

Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username, "Membership Provider"), roles);

我已经省略了这个验证码。

要从服务方法访问值,您可以调用

Thread.CurrentPrincipal.Identity.Name


1
2018-06-19 21:13





在您链接到的MSDN页面上,还有一个描述如何插入检查器的说明以及一个示例。去引用:

通常,消息检查器由服务行为,端点行为或合同行为插入。然后,该行为将消息检查器添加到DispatchRuntime.MessageInspectors集合。

稍后您将获得以下示例:

  • 实现自定义IDispatchMessageInspector
  • 实现将检查器添加到运行时的自定义IServiceBehavior。
  • 通过.config文件配置行为。

这应该足以让你开始。否则随便问:)

如果您只想从服务中获取标题,可以尝试 OperationContext.Current.IncomingMessageHeaders


0
2018-06-16 14:10