Search code examples
c#.netangulartypescriptcors

CORS Issue with Angular and C# - POST, PUT, DELETE Not Working Despite CORS Configuration


I'm facing a CORS issue in my web application, which is built with Angular (TypeScript) and uses a C# (.NET 8) API server. While the GET method works fine, it seems that the POST, PUT, and DELETE methods are not working, and I'm receiving a CORS error in the browser.

Here is a part of my code responsible for CORS configuration:

Angular TypeScript

deleteAdmRole(key: string): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/Delete/${key}`, { withCredentials: true })
      .pipe(
        catchError((error) => {
          console.error(`Error deleting AdmRole with key ${key}:`, error);
          return throwError(() => error);
        })
      );
  }

Program.cs

const string myAllowSpecificOrigins = "_myAllowSpecificOrigins";

services.AddCors(options =>
        {
            options.AddPolicy(name: myAllowSpecificOrigins,
              builder =>
              {

                  builder.WithOrigins(
                      "https://localhost:44498", 
                      "https://localhost:44337",
                      "http://localhost:44498",
                      "http://localhost:44337")
                         .AllowAnyHeader()
                         .AllowAnyMethod()
                         .AllowCredentials();
              });
        });

        app.UseCors(myAllowSpecificOrigins);

Controler C# .NET 8



[ApiController]
[Route("api/[controller]")]
public class AdmApiController : Controller
{


    [HttpGet]
  [Route(nameof(Get))]
  public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions)
  {
    
    [HttpDelete]
    [Route(nameof(Delete) + "/{key}")]
  public async Task Delete(Guid key)
  {

When I try to call the DELETE method in Angular, I receive the following CORS error in the browser:

Access to XMLHttpRequest at 'https://localhost:44337/api/AdmApi/Delete?key=619bd863-5559-42e1-82ba-9c3b544a361b' from origin 'https://localhost:44498' 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.

Could someone help me identify what might be wrong with my CORS configuration or how I can resolve this issue to make the POST, PUT, and DELETE methods work correctly? Thank you in advance for your assistance!

EDIT, answer to questions

order of execution program.cs

    Services.EntityFramework.Configure(builder.Services, builder.Configuration, builder.Environment);

    Services.IocContainer.Configure(builder.Services);

    Services.HttpClientFactory.Configure(builder.Services, builder.Configuration);

    Services.CookiePolicy.Configure(builder.Services, builder.Configuration);

    Services.Cors.Configure(builder.Services);

    Services.Authentication.Configure(builder.Services);

    Services.Mvc.Configure(builder.Services);

    Services.Session.Configure(builder.Services);


    Middleware.HttpsRedirection.Apply(app);

    Middleware.Routing.Apply(app);

    Middleware.Cors.Apply(app);

    Middleware.Authentication.Apply(app);

    Middleware.Endpoints.Apply(app);

    Middleware.CookiePolicy.Apply(app);

with


 [HttpDelete(nameof(Delete) + "/{key}")]
  public async Task Delete(Guid key)
  {

I have the same problem


{
    "headers": {
        "normalizedNames": {},
        "lazyUpdate": null,
        "headers": {}
    },
    "status": 0,
    "statusText": "Unknown Error",
    "url": "https://localhost:44337/api/AdmApi/Delete/619bd863-5559-42e1-82ba-9c3b544a361b",
    "ok": false,
    "name": "HttpErrorResponse",
    "message": "Http failure response for https://localhost:44337/api/AdmApi/Delete/619bd863-5559-42e1-82ba-9c3b544a361b: 0 Unknown Error",
    "error": {
        "isTrusted": true
    }
}

dont work with SetIsOriginAllowed(origin => true)

my launchsettings.json:

{
  "profiles": {
    "SKWangular": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      },
      "applicationUrl": "https://localhost:44337",
      "windowsAuthentication": true,
      "anonymousAuthentication": false
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      },
      "windowsAuthentication": true,
      "anonymousAuthentication": false
    }
  },
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:1285",
      "sslPort": 44337
    }
  }
}

The first profile, 'SKWangular,' allows CORS settings for GET, DELETE, POST, PUT, and OPTION, but it doesn't enable Windows Authentication. The second profile, 'IIS Express,' only allows GET; other methods don't work and result in a CORS error, but it does have Windows Authentication enabled. How can I configure it so that both functionalities work together?

first profile, 'SKWangular: why?

HttpContext.User.Identity  --- IsAuthenticated = false 

Solution

  • try to use the following for localhost: chrome://flags/#temporary-unexpire-flags-m118

    here is the image description