How to get OperationContext from an attribute implementing IServiceBehavior/IOperationBehavior

StackOverflow https://stackoverflow.com/questions/23081150

  •  03-07-2023
  •  | 
  •  

Question

I have a Attribute implementing IServiceBehavior to secure my WCF services, like below:

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
}

The problem is in order to get the message headers, I have to get the current OperationContext but I don't know how to to do it inside the ApplyDispatchBehavior. If I do it in the methods under secure, it works.

Was it helpful?

Solution

In that case I would suggest to use Message contract: Message Contract

Or you can also use IDispatchMessageInspector: Message Inspector, or IParameterInspector as I mentioned in comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top