Click here to Skip to main content
14,937,132 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a standalone C# WCF service running as a Windows service. I have the requirement to add custom headers like X-Frame-Options to all responses. I have tried to use Message Inspector but it not invoking the "BeforeSendReply" method of "CustomHeaderMessageInspector" class. Following is the code I have implemented.

What I have tried:

C#
public class CustomHeaderMessageInspector : IDispatchMessageInspector
    {
        Dictionary<string, string=""> requiredHeaders;

        public CustomHeaderMessageInspector(Dictionary<string, string=""> headers)
        {
            requiredHeaders = headers ?? new Dictionary<string, string="">();
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            string displayText = $"Server has received the following message:\n{request}\n";
            Console.WriteLine(displayText);
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {

            var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;

            foreach (var item in requiredHeaders)
            {
                httpHeader.Headers.Add(item.Key, item.Value);
            }

            string displayText = $"Server has replied the following message:\n{reply}\n";
            Console.WriteLine(displayText);
        }       
    }




Calling the above class from the below code snippet

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
       {
           var requiredHeaders = new Dictionary<string, string>();
           requiredHeaders.Add("Access-Control-Allow", "*");
           requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
           requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,DELET,OPTION");

           #pragma warning disable CA1062 // Validate arguments of public methods
           endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
           #pragma warning restore CA1062 // Validate arguments of public methods
       }
Posted
Updated 12-May-21 22:52pm
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900