【问题标题】:Cannot Retrieve WebAPI Data无法检索 WebAPI 数据
【发布时间】:2016-09-09 02:09:07
【问题描述】:

在 Visual Studio 中,我有两个应用程序。一个是 Angular 2 网站,另一个是 WebApi 项目。我在 WebAPI 方法中有一个断点,当 Angular 服务尝试检索数据但页面上没有显示任何内容时,该断点会被命中。打开浏览器控制台出现以下错误:

XMLHttpRequest cannot load http://localhost:58949/api/people. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:62761' is therefore not allowed access.

解决此问题的最佳方法是什么?我通过创建一个同时托管 WebAPI 和 Angular 应用程序的 MVC 应用程序来完成这项工作,但我不喜欢这个解决方案。

【问题讨论】:

    标签: c# asp.net asp.net-web-api angular


    【解决方案1】:

    您必须在 web api 端启用 CORS。

    我假设您使用的是 WebApi Core。要在 web api 端启用 CORS,您必须执行以下步骤-

    首先,在 project.json 中添加依赖 - "Microsoft.AspNetCore.Cors": "1.0.0",

    然后像这样在 startup.cs 中启用 CORS-

    app.UseCors(builder => {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
    

    您可以在此处找到有关 CORS 的更多信息 - https://docs.asp.net/en/latest/security/cors.html

    看看这是否有帮助。

    【讨论】:

    • 谢谢。这样做有什么安全问题吗?
    • 如果你想限制到一个特定的来源,那么你可以这样做 - ` app.UseCors(builder => builder.WithOrigins("example.com")); `
    【解决方案2】:

    你面临的问题是浏览器默认不允许跨域请求。正如您所说,您有两个具有不同网址的网站,在您的情况下,很可能只是 localhost 上的不同端口,但这仍然算作“不同”来源,并且是一种安全措施。您始终可以允许所有来源或您的 Angular 来源访问您的 Web api:

    Access-Control-Allow-Origin: http://foo.com
    Access-Control-Allow-Methods: GET, PUT, DELETE
    

    ASP.NET 有一个内置的包可以为你做这件事,所以你不需要样板。你可以阅读更多关于它的信息here。基本上它只会像上面的示例一样向您的 Web api 响应添加一些标头。

    【讨论】:

      【解决方案3】:

      我在我的 WepApi 项目中使用它。它在 WebApiConfig.cs 中。

              // Use NuGet to add this: http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors
              config.EnableCors();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-16
        • 2020-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多