VS2017 Web应用程序CORS:Access-Control-Allow-Origin

2023-12-11

我在用着Angular 6+对于一个展示CRUD to a SQL Database。我知道Angular is a client-side framework所以我使用创建了一个网络服务Visual Studio 2017我使用的项目是web application ASP.NET Core因为我正在测试它localhost, Angular跑过去4200 port我的服务目前正在运行port 53819

因此,我(或最后尝试)启用Cross-Origin Resource Sharing (CORS)通过在我的设备上安装 CORS NUGet 包webservice并在控制器级别启用它,如下所示:

...    
namespace CIE_webservice.Controllers
    {
        [Produces("application/json")]
        [Route("api/CIE")]
        [EnableCors(origins: "http://localhost:4200/", headers: "*", methods: "*")]
        public class CIEController : Controller
        {
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
...

on my Angular App我正在使用一个简单的ajax请求如下:

$.ajax({
      url: 'http://localhost:53819/api/CIE/',
      success: function() {  console.log(" OK "); },
      error: function() {  console.log(" Error "); }
  });

据我可以获得的教程,我的代码没问题,但仍然收到错误:

Failed to load http://localhost:53819/api/CIE/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

即使 Ajax 请求有一个响应 200 OK 并且预览显示了响应 json:

enter image description here

也许我错过了一些东西,或者我没有很好地理解这个概念......如果需要更多信息来解决我的案例,请随时询问。

提前致谢。


我在一个爱好项目中也有类似的工作,所以我可以向你展示我做了什么来让它发挥作用......

我在 Startup.cs 中这样做了

app.UseCors(options => options.WithOrigins(Configuration["trustedCors"].Split(' ')).AllowAnyMethod().AllowAnyHeader());

在我的配置文件中使用这个...

“受信任的Cors”:“http://本地主机:60000 https://本地主机:60000 http://glendesktop:60000 https://glendesktop:60000"

我还记得从我的测试来看,这个案例对于 CORS 很重要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VS2017 Web应用程序CORS:Access-Control-Allow-Origin 的相关文章

随机推荐