简体   繁体   English

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

[英]CORS not enabled although configured for web API

Trying to access a local API made in web API 2.0 (asp.net) from an angular project.试图从 ZD18DAZB8624A0F5F5FZ 2.0 (asp.net) 项目中访问 web API 2.0 (asp.net) 中的本地 API。

The request results in请求导致

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. 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请求的资源。

But I don't understand as I added EnableCors to the webAPIConfig但我不明白,因为我将 EnableCors 添加到 webAPIConfig

在此处输入图像描述

and specified these in all the controllers.并在所有控制器中指定这些。 在此处输入图像描述

Is there something I could try to resolve this issue?有什么我可以尝试解决这个问题的吗? Thank you in advance.先感谢您。

CORS allows you to specify who is able to call your API. CORS 允许您指定谁可以呼叫您的 API。 So more is needed than just enabling CORS;因此,需要的不仅仅是启用 CORS; you need to set the policies.您需要设置策略。 There are a couple ways to do that:有几种方法可以做到这一点:

  1. With the [EnableCors] attribute, which can be set at either the Controller or Action level:使用[EnableCors]属性,可以在 Controller 或操作级别设置:
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
  1. For your entire application:对于您的整个应用程序:
public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("[EnableCors(origins: "http://localhost:4200", "*", "*");
    config.EnableCors(cors);
}

You can set the origin to "*" to allow any website to make requests to your API, but be careful with that.可以将来源设置为"*"以允许任何网站向您的 API 发出请求,但请注意这一点。

More information here: Enable cross-origin requests in ASP.NET Web API 2更多信息在这里: 在 ASP.NET Web API 2 中启用跨域请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM