Home  >  Article  >  Web Front-end  >  Why Does IIS7 Return a 405 Method Not Allowed Error When Enabling CORS?

Why Does IIS7 Return a 405 Method Not Allowed Error When Enabling CORS?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 19:52:02996browse

Why Does IIS7 Return a 405 Method Not Allowed Error When Enabling CORS?

Enabling Cross-Origin Resource Sharing on IIS7

Enabling Cross-Origin Resource Sharing (CORS) on IIS7 is necessary to allow asynchronous resource requests to be made across different origins, overcoming browser security restrictions. However, problems can arise when IIS7 returns a 405 Method Not Allowed error prior to a successful 200 response.

Resolving the 405 Method Not Allowed Error

The 405 error typically occurs because IIS7 handles the HTTP OPTIONS response, which precedes the actual request, instead of forwarding it to your application. To correct this:

  1. Navigate to your site's Handler Mappings in IIS7.
  2. Locate and double-click the "OPTIONSVerbHandler" entry.
  3. Change the "ProtocolSupportModule" to "IsapiHandler".
  4. Set the executable path to:
    %windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll.

With these changes, IIS7 will forward the HTTP OPTIONS verb to your application.

Alternative Solution: Handling OPTIONS Verb in BeginRequest

Alternatively, you can handle the HTTP OPTIONS verb manually in your application's BeginRequest method:

<code class="c#">protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        // Handle HTTP OPTIONS pre-flight request
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}</code>

By implementing one of these approaches, you can enable CORS on IIS7 and resolve the 405 error to ensure successful cross-origin requests.

The above is the detailed content of Why Does IIS7 Return a 405 Method Not Allowed Error When Enabling CORS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn