尽管为 Web 配置,但 CORS 未启用 API

CORS not enabled although configured for web API

正在尝试从 angular 项目访问在 Web API 2.0 (asp.net) 中制作的本地 API。

请求结果

Access to XMLHttpRequest at 'http://localhost:50581/MD/GetUserMD' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是我不明白,因为我在网络上添加了 EnableCorsAPIConfig

并在所有控制器中指定了这些。

我可以尝试解决这个问题吗? 提前谢谢你。

CORS 允许您指定谁可以调用您的 API。因此,需要的不仅仅是启用 CORS;您需要设置策略。有几种方法可以做到这一点:

  1. 使用 [EnableCors] 属性,可以在 Controller 或 Action 级别设置:
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
  1. 对于您的整个应用程序:
public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("[EnableCors(origins: "http://localhost:4200", "*", "*");
    config.EnableCors(cors);
}

可以将来源设置为"*"以允许任何网站向您的API发出请求,但要小心。

这里有更多信息:Enable cross-origin requests in ASP.NET Web API 2