gpt4 book ai didi

asp.net-core - 在 JwtBearerEvents.OnAuthenticationFailed 中发送响应正文

转载 作者:行者123 更新时间:2023-12-03 16:24:56 25 4
gpt4 key购买 nike

我有一个使用 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 cannot be set because the response has already started.



有了这行注释:

at WebCsProj.Infrastructure.RequestMetadataMiddelware.<>c.<b__0_0>d.MoveNext() in 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:
});
}
}

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

最佳答案

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

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

return Task.CompletedTask;
}

关于asp.net-core - 在 JwtBearerEvents.OnAuthenticationFailed 中发送响应正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com