0

I sent request from angular project to web api .net cor 2.2.

And I get this error:

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

Here is web.config file in my web api .net cor 2.2:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" arguments="-argFile IISExeLauncherArgs.txt" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
  </system.webServer>
</configuration>

Any idea what cause to error above?

coder
  • 8,346
  • 16
  • 39
  • 53
Michael
  • 13,950
  • 57
  • 145
  • 288

1 Answers1

0

I grabbed a explanation to this from ASP.NET Core DOC also it has been mentioned by R. Richards as a comment

Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site. Sometimes, you might want to allow other sites make cross-origin requests to your app. For more information, see the Mozilla CORS article.

I was able to fix it by using

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

in Configure method of Startup.cs like bellow code.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     if (env.IsDevelopment())
     {
          app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseHsts();
     }

     app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
     app.UseHttpsRedirection();
     app.UseMvc();
}
coder
  • 8,346
  • 16
  • 39
  • 53