skip to Main Content

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.

enter image description here

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


  1. Chosen as BEST ANSWER

    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.


  2. builder.Services.AddCors(options => options.AddPolicy(name: "AppOrigins",
    policy => { policy.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader(); }));
    
    app.UseCors("AppOrigins");
    

    https://github.com/mammadkoma/WebApi/blob/master/WebApi/Program.cs

    Order of services and middlewares are important.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search