"The requested resource does not support http method 'OPTIONS'" when using EnableCors

Viewed 12986

I want to enable CORS on one specific action in an Asp.net Web Api. Here's how I'm trying to do it:

[Route("api/mycontroller/myaction")]
[HttpPost]
[EnableCors("https://example.com", "*", "post")]
public async Task<IHttpActionResult> MyAction()
{
    ...
}

But when I send an OPTIONS request to the route, I get back an error: "The requested resource does not support http method 'OPTIONS'." I also tried removing the [HttpPost] annotation to no avail. What am I missing?

3 Answers

For me, I added the following headers to the request by adding the following code to the Application_BeginRequest function of the Global.asax.cs file:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin", StringComparer.CurrentCultureIgnoreCase)
        && Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Headers", "content-type", "accept", "pragma", "cache-control", "authorization");
        Response.End();
    }
}

I have little idea why this works. Out of curiosity, I tried adding all headers by using an asterisk but then Web API complained that the Authorization header was missing.

Related