I have a WCF Restful service that I host as a Windows service. I want to add cross-domain support to my service. However, I can do this easily when I use the global.asax file. But I want to host my service as a Windows service.
I created a project that serves my service as a Windows service. Now the problem I am facing is that now I cannot add cross-domain support. I tried all possible solutions that I could find through the app.config file, but no one works. I tried the solutions on these links:
dotnet tricks
enable-cors.org
I tried to customize the header in the code using the following function, calling it in each service contract method.
private static void SetResponseHeader() { WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache, no-store"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Request-Methods", "GET, POST, PUT, DELETE, OPTIONS"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept"); }
Interface:
namespace ReaderService { [ServiceContract] public interface INFCReader { [OperationContract] [WebInvoke(UriTemplate = "GetLogin", Method = "POST")] GetLoginResults GetLogin(DisplayRequest dispRequest); }
Here DisplayRequest is a class.
Please help the guys. Let me know if anyone wants to look at any other code.
Thank you very much.
EDIT :::
Thank you very much for your reply. I created a MessageInspector class that implements IDispactchMessageInspector. I have code in the MessageInspector class.
public class MessageInspector : IDispatchMessageInspector { public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); } return null; } }
The error I am getting now is "The object reference is not installed in the object instance." The error in this line of the above code is
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
All I want to do is add CORS support for my web service. Please let me know if I am doing this correctly. OR is there any other way to do the same.