Search code examples
asp.netiiscorspreflight

Enable CORS preflight ASP.NET on IIS


I have the binaries only for an ASP.NET application and I am trying to bring it up on my local. I am having some CORS issues while trying to bring it up.

Access to XMLHttpRequest at 'http://xx.xx.xx.xx:8080/webapi/' from origin 
'http://xx.xx.xx.xx:8089' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried several things including installing the CORS module on IIS from here https://www.iis.net/downloads/microsoft/iis-cors-module

I have also tried to change my Web.Config to add the following. All I am trying to do is to just make it work to begin with so I want to allow all requests to pass through.

<system.webServer>
  <cors enabled="true">
    <add origin="*" allowed="true" />
    <add origin="http://*" allowed="true" />
  </cors>

but I still get the same error. The weird thing is, both the webapi and the ASP.NET client are on the same machine on different ports 8080 and 8089.


Solution

  • First you have to make sure you have successfully installed the cors module, then you need to add the following configuration in the web.config of the application:

     <system.webServer> 
       <cors enabled="true">
        <add origin="*" allowed="true" />
      </cors>
      </system.webServer>
    

    This configuration node is under the configuration node.

    If it is still not resolved, you can also solve the cross-domain problem by adding the following code to the Global file:

    protected void Application_BeginRequest(object sender, EventArgs e)
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    
                {
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "*");
    
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
    
                    HttpContext.Current.Response.End();
                }
    
            }