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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();
            }

        }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x