Ive got a C# .NET MVC solution with WebApi. Now I've setup Owin and CORS(for Token based authentication) and all is working as expected.
I've also got a File Handler: File.ashx configured and the handler works perfectly locally. The problem is that when I send a request to the handler from another Origin(Via an AJAX client-side call) I get the folliwing error:
XMLHttpRequest cannot load http://localhost:1234/Handlers/File.ashx. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1234' is therefore not allowed access. The response had HTTP status code 405.
Now when the browser sends the OPTIONS request it is clear that the Access Control Headers are not returned to the client.
Ive taken a look at the below link: Header not being set for OPTIONS Ajax request which suggests that I return the appropriate headers via the handler itself.
But when debugging I've noticed that the ProcessRequest
Method is not even being hit.
if (context.Request.HttpMethod == "OPTIONS")
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
}
My question is where do I control/intercept the OPTIONS request and return the appropriate headers?
Note that I only want to enbale CORS on WebApi(which is already working) and my File Handler.
I also just discovered that if you're running your project from Visual Studio and you're debugging, you need to have started your Visual Studio as Administrator.
You should ensure to use either the ProcessRequest method
1)
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
or the
2)
web.config
file
For anyone wondering on how to solve this issue:
Add an event handler to BeginRequest in the Global.asax.cs Constructor and manipulate your response headers based on your request there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With