.netwcfidispatchmessageinspector

Add Message Inspector for methods with attribute


Is it possible to only have a message inspector on certain service methods which have a custom attribute applied to them? All of the examples I've seen online add a message inspector as a behavior extension which gets applied to every method on the service.


Solution

  • I'm not sure if it's possible to apply the inspector to only a limited set of methods however you could try creating a regular message inspector which would check whether the target method has a custom attribute applied:

    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
            string actionName = request.Headers.Action.Substring(request.Headers.Action.LastIndexOf('/') + 1);
            if (!string.IsNullOrEmpty(actionName))
            {
                var methodInfo = instanceContext.Host.Description.ServiceType.GetMethod(actionName);
                if (methodInfo != null)
                {
                    var customAttributes = methodInfo.GetCustomAttributes(false);
                    if (customAttributes.Any(ca => ca.GetType().Equals(typeof(MyCustomAttribute))))
                    { 
    
                    }
                }
            }
            ...
    

    This is just a quick and dirty implementation you'll probably want to refactor a bit. You might also want to abstract away the filtering process outside the inspector itself, maybe have a Chain of Responsibility of some kind to handle it. Hope that helps.