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:
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
}