在JwtBearerEvents.OnAuthenticationFailed中发送响应主体

时间:2018-03-28 14:22:01

标签: 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);
                }
            };
        }

验证失败时,该代码会执行,但不会返回响应。我得到a stack trace

这是消息:

  

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

请注意这一点:

  

at WebCsProj.Infrastructure.RequestMetadataMiddelware。<> c。< b__0_0> d.MoveNext()在C:\ Users \ justin.dearing \ source \ repos \ my-solution \ WebCsProj \ Infrastructure \ RequestMetadataMiddelware.cs :第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:
        });
    }
}

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

1 个答案:

答案 0 :(得分:2)

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

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

    return Task.CompletedTask;
}