我在这方面束手无策。我已经在 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/