Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Add CORS headers to ashx File Handler

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.

like image 798
Wr4i7h Avatar asked Jun 07 '17 16:06

Wr4i7h


2 Answers

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

like image 131
Malisa Ncube Avatar answered Nov 12 '22 09:11

Malisa Ncube


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.

like image 38
Wr4i7h Avatar answered Nov 12 '22 09:11

Wr4i7h