Home  >  Article  >  Web Front-end  >  How do I enable Cross-Origin Resource Sharing on IIS 7?

How do I enable Cross-Origin Resource Sharing on IIS 7?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 01:53:27809browse

How do I enable Cross-Origin Resource Sharing on IIS 7?

Enabling Cross-Origin Resource Sharing on IIS 7

Cross-Origin Resource Sharing (CORS) is a mechanism that allows client applications to access resources from different domains. By default, browsers restrict cross-origin requests for security reasons. To enable CORS on IIS 7, follow these steps:

  1. Configure the Web.config file:

    Add the following custom headers to the section:

    <code class="xml"><customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
    </customHeaders></code>
  2. Handle HTTP OPTIONS requests:

    By default, IIS 7 handles HTTP OPTIONS requests. To allow your application to handle these requests, modify the protocol support module for the 'OPTIONSVerbHandler' in IIS Manager:

    • Navigate to Handler Mappings for the site
    • Scroll down to 'OPTIONSVerbHandler'
    • Change 'ProtocolSupportModule' to 'IsapiHandler'
    • Set the executable: %windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll
  3. Alternatively, respond to HTTP OPTIONS in code:

    Add the following code to the Application_BeginRequest method in your application:

    <code class="csharp">protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            // Handle "pre-flight" OPTIONS call
            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 following these steps, you can enable CORS on IIS 7 and allow cross-domain resource sharing in your applications.

The above is the detailed content of How do I enable Cross-Origin Resource Sharing on IIS 7?. 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