Enabling Cross-Origin Resource Sharing (CORS) on IIS7
Cross-Origin Resource Sharing (CORS) allows web applications running on different origins to make HTTP requests to each other. However, by default, XHR requests to other domains are not permitted.
Enabling CORS on the Target Domain
To enable CORS on the target domain, add the following custom headers to the web.config file:
<code class="xml"><?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <httpProtocol> <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> </httpProtocol> </system.webServer> </configuration></code>
IIS7 Configuration
After enabling CORS on the target domain, you may still encounter a 405 Method Not Allowed response. This is likely due to IIS7 handling the HTTP OPTIONS response instead of your application.
To resolve this:
Alternatively, Respond to HTTP OPTIONS in Code
You can also respond to the HTTP OPTIONS verb in your BeginRequest method:
<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") { // 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>
The above is the detailed content of How to Enable Cross-Origin Resource Sharing (CORS) on IIS7?. For more information, please follow other related articles on the PHP Chinese website!