【问题标题】:.NET Core 2.0 - Still seeing No 'Access-Control-Allow-Origin' header error.NET Core 2.0 - 仍然看到没有“Access-Control-Allow-Origin”标头错误
【发布时间】:2018-11-27 20:57:01
【问题描述】:

我对此一无所知。我已经研究了关于 SO 的类似问题的其他答案,但运气不佳。

我相当确定我已正确启用 CORS 以允许来自所有来源的传入请求(在本例中为 POST 请求),但我看到以下错误:

无法加载http://localhost:5000/expenses:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 使用权。响应的 HTTP 状态代码为 500。

以下是我在 webAPI 项目中启用 CORS 的方法:

Startup.cs 中的相关方法

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc();

            services.AddDbContext<ExpensesDbContext>(options =>
                                                    options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<IBaseDa<Accounts>, AccountsDataAccess>();
            services.AddTransient<IExpensesDa, ExpensesDa>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            env.EnvironmentName = "Development";

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

            app.UseMvc();
        }

如果我使用的是.AllowAnyOrigin() 和.AllowAnyMethod(),为什么会出现上述错误?

【问题讨论】:

  • 看过asp.net core 2.0的回答in this question?
  • @JonathonChase 是的,我确实尝试定义我的策略并为其命名,等等对我不起作用;看到同样的错误
  • @mjwills 使用此 api 的前端位于端口 4200 后面。我试过 .WithOrigin(“http://localhost:4200”。没用:(
  • 看起来 HTTP 状态代码 500 可能是这里的问题 - Fiddler 将响应显示为什么?
  • 你在使用 chrome 吗?

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


【解决方案1】:

在这种情况下我有一段时间摸不着头脑。我正确启用了 CORS,但一些调用仍然返回 Access-Control-Allow-Origin 错误。我发现了问题......偷偷摸摸的偷偷摸摸的问题......

我们的问题是由我们如何使用app.UseExceptionHandler 引起的。具体来说,这是我们使用的代码,除了我们的原始代码没有context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 行。

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
        var exception = errorFeature.Error;

        var problemDetails = new ProblemDetails
        {
            Title = R.ErrorUnexpected,
            Status = status,
            Detail =
              $"{exception.Message} {exception.InnerException?.Message}"
        };

        context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        context.Response.StatusCode = problemDetails.Status.GetValueOrDefault();
        context.Response.WriteJson(problemDetails, "application/problem+json");

        await Task.CompletedTask;
    });
});

app.UseExceptionHandler 是一个比控制器动作低得多的功能,因此不参与任何与 CORS 相关的本机操作。添加context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 解决了这个问题。

【讨论】:

  • 这帮助我调试了我的问题,基本上只是说你的标题中提到的相同错误。非常感谢
  • 这应该被标记为有效答案,我花了几个小时才找到解决方案。最烦人的是,有效的请求以正确的方式返回。
【解决方案2】:

我的水晶球告诉我,在您的 C# 代码中某处在执行时出现错误,这样服务的“返回”语句就永远不会执行。因此,请调试您的代码并修复错误,以便将响应返回给浏览器。

【讨论】:

    【解决方案3】:

    netCore2.0 (http://localhost:5000/) + Angular (http://localhost:4200) + chrome = Access-Control-Allow-Origin 的组合。我之前遇到过这个问题,我花了 3 天时间才意识到 chrome 总是会抛出这个错误。我认为这是因为 chrome 将 localhost 视为来源,而忽略了端口,即使中间件明确告诉它,尤其是在 POST 请求上。

    我会尝试在您的 startup.cs 中定义一个策略配置服务:

      public void ConfigureServices(IServiceCollection services)
            {
      //add cors service
                services.AddCors(options => options.AddPolicy("Cors",
                    builder =>
                    {
                        builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    }));
    

    然后在您的配置方法中我会添加:

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                //authentication added 
                app.UseAuthentication();
    
                app.UseCors("Cors");
                app.UseMvc();
            }
    

    ...这很可能不会起作用,但是任何人都可以尝试...这让我发疯了,我需要满足于查看请求是否甚至尝试访问 asp.netCore 后端: 我用过

    如果你真的想看我会清除你的缓存和 cookie 然后添加 IHttpContextAccessor 对请求中发生的事情进行低级别控制。 在我遇到同样问题的困境中,我需要角度来发送图像。我得到了 annyoing 起源错误然后通过实验我通过将 IHttpContextAccessor 注入我的控制器和

    调试

    public void ConfigureServices(IServiceCollection services)
    {
      //add cors service
                    services.AddCors(options => options.AddPolicy("Cors",
                        builder =>
                        {
                            builder.AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                        }));
    
        services.AddMvc();
    
             // register an IHttpContextAccessor so we can access the current
                // HttpContext in services by injecting it
                //---we use to this pull out the contents of the request
    
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }
    

    你想把它注入到你的任何控制器中

    用于检索 POST 请求的 json 对象。我将使用该示例作为 Home 控制器:

    public class HomeController : Controller
        {
    
            // make a read only field
            private readonly IHttpContextAccessor _httpContextAccessor;
    
        //create ctor for controller and inject it
        public UserService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        // now in your post method use this to see what the if anything came in through the request:
        public async Task<IActionResult> Picload(IFormFile file){//---always null
    
        // in my problem I was loading and image from.
        var file =  _httpContextAccessor.HttpContext.Request.Form.Files[0];
    }
    

    使用它让我可以访问图像 chrome 给我一个 Origin 错误。

    【讨论】:

    • 谢谢。你的解决方案对我有用。我刚刚根据您的解决方案更改了我的“startup.cs”文件。它的工作原理。
    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2016-09-03
    • 2017-09-19
    • 2015-04-02
    相关资源
    最近更新 更多