My project works perfectly on Visual Studio but after I published the ASP.NET Core Web API and built the Angular code, I cannot access to API functions because of this error:
Access to XMLHttpRequest at ‘http://localhost:7173/login/login’ from origin ‘http://localhost:44413’ 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.
And I checked on Network tab and saw there was no http header added to the request.
I really don’t know why this happens after publish.
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
......
app.UseCors(MyAllowSpecificOrigins);
and this is on angular call:
let httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*'
})
};
this.http.post<string>('http://localhost:7173/login/login', this.user, httpOptions)
.subscribe(results => { console.log(results); },
error => console.log(error));
and this is my proxy json:
{
"/*": {
"target": "http://localhost:7173/",
"secure": false,
"logLevel": "debug"
}
}
I do everything and change everything but the error is still the same.
Everything works perfectly on visual studio but after publishing I don’t know what the reason is.
2
Answers
I finally did it by the manual in this video:
https://www.youtube.com/watch?v=Lt3wve_nb0g
It was not related to Cors or something else, the problem was that backend ASP.NET Core Web API didn't run. And in IIS, in pools, we should set 32-Bit application activation true in the related pool.
And for publishing we have to run Visual Studio as Administrator.
https://github.com/mammadkoma/WebApi/blob/master/WebApi/Program.cs
Order of services and middlewares are important.