c# - IExceptionFilter 处理程序在 ASP.NET Core 3.1 Blazor(服务器端)中不起作用

标签 c# asp.net-mvc asp.net-core

我正在测试在 ASP.NET Core 2.2 网站中使用的异常过滤器的功能。它是对 Microsoft.Identity.Web 中的 AuthorizeForScopesAttribute 类的轻微修改。示例存储库。

应该发生的情况是,当我们尝试从缓存中获取 token 时,它将抛出 MsalUiRequiredException ,该异常应该被过滤器捕获并强制重新身份验证。 TokenAcquisitioncatches the exception并抛出,但过滤器从未捕获它。

为了测试 3.1,我创建了一个简单的 Blazor(服务器端)网站,添加了对 Microsoft.Identity.Web 的引用,并尝试调用 Microsoft Graph API;类似于 this example

ASP.NET Core 2.2 实现(Startup.cs):

services.AddMvc(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
    options.Filters.Add(new AuthorizeForScopesAttribute(new string[] {ScopeConstants.ScopeUserRead}));
});

ASP.NET Core 3.1 实现(Startup.cs):

services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
    options.Filters.Add(new AuthorizeForScopesAttribute(new[] {ScopeConstants.ScopeUserRead}));
});

Microsoft.Identity.Web 的示例存储库依赖于用属性装饰 Controller ,由于我在 2.2 Web 应用程序中使用 Razor 页面,在 3.1 Web 应用程序中使用 Blazor(服务器端),所以我必须修改如下:

  • ExceptionFilterAttribute替换为IExceptionFilter
  • 添加了一个构造函数并在 Startup.cs 中提供了 Scopes 属性
  • 由于这不是抽象类的实现(现在使用接口(interface)),因此我删除了 OnException 方法中的 override 语句,因此它只是 public void OnException(ExceptionContext context) 现在。

我一直在与一位维护该存储库的同事合作,但我们都对为什么它没有被触发感到困惑。由于 3.1 不再使用“UseMvc”语句,这是否是正确的实现?据我所知it looks correct .

仅供引用:我意识到类名也没有反射(reflect)出这不再是一个属性的事实,但我现在只是保持名称不变。

最佳答案

事实证明,Blazor 应用程序不支持 ASP.NET Core 中的异常筛选器。我将根据 GH 的指导制定替代方案,并相应地更新这篇文章。

官方字样:https://github.com/dotnet/aspnetcore/issues/18761

关于c# - IExceptionFilter 处理程序在 ASP.NET Core 3.1 Blazor(服务器端)中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882877/

相关文章:

c# - 未知模块中发生类型为 'System.IO.FileNotFoundException' 的未处理异常”

c# - asp.net mvc 缓存删除整个网站中的输出缓存

c# - ASP.Net WEB API 无法从移动设备发布大型 JSON 数据

c# - ASP.NET Core 中间件向 Controller 传递参数

c# - 在 ASP.NET MVC C# 中使用 Jquery 更新局部 View

C# 将 ListBox 中的所有项目保存到文本文件

c# - SelectListItem selected = true 在 View 中不工作

asp.net-mvc - 将MVC中的未经授权的页面访问重定向到自定义 View

authentication - ASP.Net Core、Angular2 和基于 token 的身份验证

asp.net-identity - Microsoft.AspNet.Identity 3 中 ClaimsAuthorizationAttribute 的等效项