如何从实现IServiceBehavior / IOperationBehavior的属性获取OperationContext

时间:2014-04-15 10:33:30

标签: c# wcf wcf-extensions

我有一个实现IServiceBehavior的属性来保护我的WCF服务,如下所示:

public class AuthorizedServiceAttribute : Attribute, IServiceBehavior
{
    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var token = string.Empty; // to do: get the token from message headers

        foreach (var operation in serviceHostBase.Description.Endpoints
            .SelectMany(endpoint => endpoint.Contract.Operations))
        {
            operation.Behaviors.Add(new AuthorizedMethodAttribute { Token = token });
        }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    { }

    #endregion
}

问题是为了获取消息头,我必须获取当前的OperationContext但我不知道如何在ApplyDispatchBehavior中执行它。如果我在安全下的方法中这样做,它就可以工作。

1 个答案:

答案 0 :(得分:0)

在这种情况下,我建议使用消息合约:Message Contract

或者你也可以像我在评论中提到的那样使用IDispatchMessageInspector:Message Inspector或IParameterInspector。