Angular 和 C# 的 CORS 问题 - 尽管配置了 CORS,但 POST、PUT、DELETE 不起作用

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

提问人:Falcon 提问时间:11/17/2023 最后编辑:Falcon 更新时间:11/18/2023 访问量:87

问:

我在我的 Web 应用程序中遇到了 CORS 问题,该应用程序是使用 Angular (TypeScript) 构建并使用 C# (.NET 8) API 服务器的。虽然 GET 方法工作正常,但似乎 POST、PUT 和 DELETE 方法不起作用,并且我在浏览器中收到 CORS 错误。

以下是我负责 CORS 配置的代码的一部分:

Angular 打字稿

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);
        })
      );
  }

程序.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);

控制器 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)
  {

当我尝试在 Angular 中调用 DELETE 方法时,我在浏览器中收到以下 CORS 错误:

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.

有人可以帮助我确定我的 CORS 配置可能存在什么问题,或者我如何解决此问题以使 POST、PUT 和 DELETE 方法正常工作吗?提前感谢您的帮助!

编辑,回答问题

执行程序的顺序 .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);


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

我有同样的问题


{
    "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
    }
}

不适用于 SetIsOriginAllowed(origin => true)

我的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
    }
  }
}

第一个配置文件“SKWangular”允许 GET、DELETE、POST、PUT 和 OPTION 的 CORS 设置,但不启用 Windows 身份验证。第二个配置文件“IIS Express”仅允许 GET;其他方法不起作用并导致 CORS 错误,但它确实启用了 Windows 身份验证。如何配置它,以便这两个功能协同工作?

第一个配置文件,“SKWangular:为什么?

HttpContext.User.Identity  --- IsAuthenticated = false 
C# .NET Angular TypeScript CORS

评论

0赞 sommmen 11/17/2023
检查 webapi 是否有任何错误日志,如果发生异常,cors 可能会隐藏错误。此外,是否应该设置删除终结点 nog,以便正确绑定密钥?和/或添加到参数中。[HttpDelet("Delete/{key}")][FromRoute]
0赞 JineappleAra 11/17/2023
在中间件管道的哪个点调用 app。UseCors?必须在定义路由之前完成此操作。
0赞 Magnus 11/17/2023
它适用于 AllowAnyOrigin() 吗?
0赞 Falcon 11/17/2023
@sommmen或不工作.@JineappleAra我用它更新我的帖子。@Magnus不起作用[HttpDelete("Delete/{key}")][HttpDelete] [Route(nameof(Delete) + "/{key}")]

答:

-1赞 Hope 11/17/2023 #1

尝试对 localhost 使用以下命令: chrome://flags/#temporary-unexpire-flags-m118

这是图像说明

评论

0赞 derpirscher 11/17/2023
这将如何解决缺少 CORS 标头的问题?