在 JwtBearerEvents.OnAuthenticationFailed 中发送响应正文

Jus*_*ing 6 asp.net-core

我有一个使用 OAuth Bearer Auth 和 Azure AD V2 端点的 .NET Core 2.0 应用程序。如果出现 500 错误,我希望将异常消息返回给用户。我有以下代码来做到这一点:

            options.Events = new JwtBearerEvents
            {
                // This used to be options.Notifications = new OpenIdConnectAuthenticationNotifications
                OnTokenValidated = AzureAdAuthCallbacks.TokenValidated,
                OnAuthenticationFailed = async context =>
                {
                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync(context.Exception.Message);
                }
            };
        }
Run Code Online (Sandbox Code Playgroud)

当验证失败时,该代码会执行,但不会返回响应。我得到一个堆栈跟踪

这是消息:

System.InvalidOperationException:无法设置 StatusCode,因为响应已经开始。

有了这行注释:

在 WebCsProj.Infrastructure.RequestMetadataMiddelware.<>c.<b__0_0>d.MoveNext() 在 C:\Users\justin.dearing\source\repos\my-solution\WebCsProj\Infrastructure\RequestMetadataMiddelware.cs:line XXX

但是,该中间件成功完成:

public static class RequestMetadataMiddelware
{
    public static IApplicationBuilder UseRequestMetadataExtractor(this IApplicationBuilder app)
    {
        return app.Use(async (context, next) =>
        {
            // I don't set a status code here.
            // Some code that works is here
            await next.Invoke(); // The debugger indicates the code makes it here:
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以做些什么来调试这个或设置响应的正确方法是什么?有没有办法阻止中间件链在 中执行OnAuthenticationFailed

And*_*toy 6

您可以在使用OnStarting方法调用下一个中间件后编写响应正文:

OnAuthenticationFailed = context =>
{
    context.Response.OnStarting(async () =>
    {
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync(context.Exception.Message);
    });

    return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)