c# - .NET Core 2.0 - 仍然看到没有 'Access-Control-Allow-Origin' header 错误

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

我在这方面束手无策。我已经在 SO 上研究了类似问题的其他答案,但运气不佳。

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

Failed to load http://localhost:5000/expenses: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 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(),为什么我会看到上面的错误?

最佳答案

我对这里的情况摸不着头脑了一段时间。我已正确启用 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 是比 Controller 操作级别低得多的函数,因此不参与任何与 CORS 相关的本地操作。添加 context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 解决了这个问题。

关于c# - .NET Core 2.0 - 仍然看到没有 'Access-Control-Allow-Origin' header 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919179/

相关文章:

c# - 将 JSON 值写入 SQL 数据库

c# - 托管代码中是否可能发生内存泄漏? (特别是 C# 3.0)

c# - 您可以在 C# 中实例化泛型类型参数的嵌套类型吗?

c# - ASP.Net MVC 4 Bundles - 在路径名中使用变量

c# - WinStore : Slide a Grid on- and off-screen

asp.net - .isproj 无法打开,因为其项目类型 (.isproj) 不受支持

c# - 如何启用迁移以在 MVC4 中更新我的数据库?

c# - 最小化 ASP.Net 中的 ViewState 大小,在构造函数中初始化控件值与 OnInit 之间有区别吗?

c# - 根据条件循环两个 XElements

.net - 为什么当用户放大 Excel 时 WinForms 控件被禁用?