"The requested resource does not support the" OPTIONS "HTTP method when using EnableCors

I want to incorporate CORS into one specific action in App.net Web Api. Here is how I am trying to do this:

[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 return an error message: "The requested resource does not support the http method" OPTIONS "." I also tried removing the [HttpPost] annotation to no avail. What am I missing?

+7
source share
3 answers

You probably missed a higher level call to HttpConfiguration.EnableCors, as described here: https://enable-cors.org/server_aspnet.html .

Add this code to your configuration:

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}
+5

OPTIONS , - , , web.config:

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

:

<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
  modules="IsapiModule" requireAccess="None"
  scriptProcessor="C:\Windows\System32\inetsrv\asp.dll"
  resourceType="Unspecified" />

IIS CORS Preflight OPTIONS.

, , :

 <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
   modules="ProtocolSupportModule" requireAccess="None" />

global.asax , global.asax :

if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
    filterContext.HttpContext.Response.Flush();
}

... - , :

if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase)
    && Request.HttpMethod == "OPTIONS") {
    Response.Flush();
}

, , :

  • , OPTIONS / , / - ,
  • , OPTIONS
  • OPTIONS Response.Flush()

, , , :

public HttpResponseMessage Options()
{
    var response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK
    };
    return response;
}
+5

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 to add all the headers using an asterisk, but then the web API complained about the lack of an authorization header.

+5
source

Source: https://habr.com/ru/post/1683469/


All Articles