Error Massage: Access to XMLHttpRequest at ‘URL’ from origin ‘URL’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I have a .net5 web_api application and frontend develop using reactjs. This web_api work perfectly on localhost. I used ionos windows hosting. when I host my web_app on IIS server then the error comes.
I have tried on web.config file. Like that
<httpProtocol>
<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>
</httpProtocol>
I have tried on startup.cs file. Like that
services.AddCors(opt =>
{
opt.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:3000")
.WithHeaders(HeaderNames.ContentType, "x-custom-header", HeaderNames.CacheControl)
.WithMethods("POST", "PUT", "DELETE", "GET", "OPTIONS")
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
.Build();
});
});
and
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
I’m trying to solve this error various way. But i can’t do it.
Please help me to solve this.
2
Answers
In the end, I solved this error ☺️. this error comes from "WebDAVModule". I just remove this module from web.config file.
Add modules-remover before handlers.
web.config
I created a new asp.net core 5 api project and enabled cors policy by adding code in startup.cs like below, and then publish the project to IIS in my virtual machine. I called the api in my asp.net core MVC project and it worked well for me. I think you may follow this official document or my code to check if you missed some configuration.