未为内部服务器错误响应 ASP.NET Core 3.1 设置 CORS 标头 [英] CORS header not being set for internal server error response ASP.NET Core 3.1

查看:16
本文介绍了未为内部服务器错误响应 ASP.NET Core 3.1 设置 CORS 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 CORS 配置:

Here is my CORS configuration:

services.AddCors(options =>
{
    options.AddPolicy(name: "AllowedOrigins",
        policyBuilder =>
        {
            var urls = Configuration.GetSection("Host:AllowedOrigins").Get<List<string>>();
            policyBuilder.WithOrigins(urls.ToArray())
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials();
        });
});

Configure方法中:

app.UseRouting();

app.UseCors("AllowedOrigins");
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

对于内部服务器错误,响应中没有 access-control-* 标头.据我所知,这个问题应该从 ASP.NET Core 2.2 开始修复.

For internal server error, there are no access-control-* headers in the response. As far as I know, this issue should be fixed since ASP.NET Core 2.2.

我为 ASP.NET Core 3.1 创建了一个问题,您可以跟踪问题.

I created an issue for ASP.NET Core 3.1 and you can track the issue.

推荐答案

您需要在启动时显式调用 app.UseExceptionHandler(...).

You need to explicitly call app.UseExceptionHandler(...) in your startup.

如果不这样做,则未处理的异常会在调用堆栈中一直冒泡到 Kestrel.并且 Kestrel 不会调用连接到 HttpContext.Response.OnStarting(...) 的委托.CorsMiddleware(以及许多 其他中间件)使用 OnStarting 将信息添加到响应中.

If you do not, then unhandled exceptions bubble up the call stack all the way to Kestrel. And Kestrel does not call the delegates hooked up to HttpContext.Response.OnStarting(...). CorsMiddleware (and many other middleware) use OnStarting to hook into adding information to the response.

这篇关于未为内部服务器错误响应 ASP.NET Core 3.1 设置 CORS 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆