【问题标题】:'Access-Control-Allow-Origin' header is present on the requested resource请求的资源上存在“Access-Control-Allow-Origin”标头
【发布时间】:2020-07-10 10:53:50
【问题描述】:

我正在尝试从 Angular 应用程序连接到我的 .net 核心 API。当我尝试这样做时,我收到一条错误消息:

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

以下是来自我的 Angular 应用程序的控制台消息:

这是我为解决错误所做的。我在 startup.cs 文件的 ConfigureServices 方法中添加了 services.addCors:

public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options =>
        {
            options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers();
           services.AddDbContext<db_recloadContext>();

    }

在配置方法中,我输入了以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
           app.UseCors("AllowAnyCorsPolicy");
           app.UseHttpsRedirection();
           app.UseRouting();
           app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

在我的控制器中,我有以下代码:

namespace RecLoad.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAnyCorsPolicy")]
    public class RecLoadPrimeController : ControllerBase
    {
        private readonly db_recloadContext _context;

        public RecLoadPrimeController(db_recloadContext context)
        {

            _context = context;
        }

我遵循了 Microsoft 文档中给出的说明以及其中一篇 stackoverflow 帖子:

https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api

和微软的文章:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

我花了很多时间浏览其他文档并在 startup.cs 文件中尝试了不同的代码,但这个错误并没有消失。

下面是我运行良好的 api:

[HttpGet]
       public ActionResult<string> Get()
        {

            return "This is a test";

        }

以下是我的开发者工具的标题:

我还在我的 chrome 浏览器中启用了 CORS 扩展。下图是:

我们将不胜感激。

【问题讨论】:

    标签: angular .net-core cors asp.net-core-webapi


    【解决方案1】:

    要使其发挥作用,您可以尝试以下方法:

    1) 在ConfigureServices 方法中,调用AddCors 配置CORS 服务,最初允许任何来源:

    services.AddCors(options => 
    {
        options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
    });
    

    2) 在Configure 方法中添加UseCors,这会将中间件添加到Web 应用程序管道中:

    app.UseRouting();
    app.UseCors("AllowAnyCorsPolicy");
    app.UseMvc();
    

    由于 ASP.NET Core 3.1 .UseCors() 需要在.UseRouting() 之后调用,如https://github.com/dotnet/aspnetcore/issues/17830 中所述。

    当此初始配置正常工作时,以后可以根据您的要求对其进行修改。

    【讨论】:

    • 我将您提供给我的确切代码放入我的应用程序中。我收到另一个错误:InvalidOperationException:端点 RecLoad.C​​ontrollers.RecLoadPrimeController.Get (RecLoad) 包含 CORS 元数据,但找不到支持 CORS 的中间件。通过在应用程序启动代码中对 Configure(..) 的调用中添加 app.UseCors() 来配置应用程序启动。对 app.UseAuthorization() 的调用必须出现在 app.UseRouting() 和 app.UseEndpoints(...) 之间。
    • 本指南在 ASP.NET 2.2 中提到这是有效的,迁移指南说您需要在 .UseRouting() 之后使用 .UseCors():github.com/dotnet/aspnetcore/issues/17830
    • 修改了答案。
    • 我将 useRouting 放在 Configure 方法中,现在当我运行 api 时,我现在遇到三个错误:1)从源 'localhost:4200' 访问 XMLHttpRequest 在 'localhost:44378/api/recloadprime' 已经被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。 2) ERR_failed 和最后一个 HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error",
    • 对此的任何帮助将不胜感激。
    猜你喜欢
    • 2016-06-30
    • 2016-10-08
    • 2013-11-29
    • 2014-07-28
    • 2014-01-19
    相关资源
    最近更新 更多