Search code examples
jqueryasp.net-web-apicorsfetch-apipreflight

Cors Errors (No 'Access-Control-Allow-Origin' / It does not have HTTP ok status.), when trying to get data from web app


I got frontend code, that gets some data from my ASP.NET Web App.

      $.ajax({  
        url: http://webApiURL,  
        method: "GET",
        contentType: "application/json;odata=verbose",  
        headers: { "accept": "application/json;odata=verbose" },  
        success: function (data) {  
          new WorkTimer(data, "o365cs-nav-centerAlign"); //code that display data further in html
        }, 
      }); 

ASP.NET Web App is very simple and code that I think maters here is:

public class HPMController : ApiController
{
    [HttpGet]
    [ActionName("WorkTime")]
    public HttpResponseMessage GetWorkTime(string param)
    {
        using (HPMEntities db = new HPMEntities())
        {
            var answer = db.Database.SqlQuery<string>("HPM.dbo.someProcedure " + param).First();
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, answer);
            response.Headers.Add("Access-Control-Allow-Origin", "*");

            return response;
        }
    }
}

Everything work fine on my development computer, and more, it's working fine on others computers in our intranet as long as web app is hosted on my IIS (win10). But when I moved web app to server (winServer2012R2), I got error in browser:

Access to XMLHttpRequest at 'http://serverURL' from origin 'http://websiteURL' 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 dig a little bit and I tried adding to web.config of web app this:

<configuration>
  <system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Methods" value="*"/>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="*"/>
        </customHeaders>
    </httpProtocol>
</configuration>

But it only got me other error:

Access to XMLHttpRequest at 'http://serverURL' from origin 'http://websiteURL' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

As far I don't know how to resolve this. It's strange to me that web app change behavior when moved on other host.


Solution

  • I figured out a solution. Problem is in version of IIS, which is 8.5 on winServer2012R2 and couldn't be upgraded on this OS version. For some reason Headers defined in code are ignored in IIS 8.5 and I couldn't figure out how to properly define them in web.config, where are not ignored. (That was reason for occur the second error) I just simply moved app on different serwer (winServer2019) and it working now.