Enabling Cross-Origin Resource Sharing on IIS7: A Comprehensive Guide
Introduction
Cross-Origin Resource Sharing (CORS) allows resources from one domain to be fetched and utilized by applications from a different origin. To enable CORS on IIS7, follow these steps:
Configuration
Add Custom Headers:
<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>
Troubleshooting
Despite the configuration, if you still receive a 405 response, it may be due to IIS7's handling of HTTP OPTIONS.
Option 1: Modify IIS7 Handler Mappings
Set the executable to:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Option 2: Handle OPTIONS Verb in Code
Override the BeginRequest method in your application code:
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 from browser 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(); } }
Conclusion
Enabling CORS on IIS7 requires both configuration updates and potential troubleshooting. By following the steps outlined above, you can empower cross-origin interactions with confidence.
The above is the detailed content of How to Enable Cross-Origin Resource Sharing (CORS) on IIS7: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!