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

查看:125
本文介绍了没有为内部服务器错误响应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开始修复./p>

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.

推荐答案

您需要在启动时显式调用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天全站免登陆