I have a WCF Restful service which I am hosting as Windows service. I want to add cross domain support to my service. However, i can do this easily when I use global.asax file. But I want to host my service as a windows service.
i have created a project which host my service as windows service. Now the problem I am facing is, I am not able to add cross domain support now. I tried all possible solutions I could find through app.config file, but none works. I have tried solutions on these links:
dotnet tricks
enable-cors.org
I tried setting the header in the code using the following function by 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 guys. Let me know if anybody want to have look at any other code.
Thanks a lot.
EDIT:::::::
Thanks a lot Thomas for your reply.
I created a class MessageInspector which implement IDispactchMessageInspector. I have following code in 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 that I am getting now is -- 'Object reference not set to an instance of an object.'
The error is at this line of the above code
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
All I want to do is add CORS support to my web service. Please let me know if I am doing it correctly. OR is there any other way to do the same.
See Question&Answers more detail:
os