asp.net-core - 如何从 ASP.Net Core 5 (Razor) 中的中间件获取页面模型的类型?

标签 asp.net-core razor-pages .net-5

我正在尝试编写一个仅适用于没有 [AllowAnonymous] 的 Razor 页面的中间件。 Model 类的属性。然而,要实现这一目标,我必须以某种方式通过 HttpContext 从中间件找出页面模型的类型。目的。我不确定这种类型信息是否存在,因为中间件在 Razor Page 之前运行,所以端点可能尚未从路径中解析。

我尝试偷看 context.Features.Get<IEndpointFeature>()?.Endpoint 内部类,但我无法找到有关端点类型的任何有用信息。

我也考虑过过滤器,但我正在修改一个现有的项目,该项目使用中间件实现许多检查,我想避免将它们重写为 IActionFilter如果可以的话。

最佳答案

您可以像下面一样使用中间件:

app.UseRouting();           
app.UseAuthentication();
app.UseAuthorization();

app.Use(async (context, next) =>
{
    var endpoint = context.GetEndpoint();
    //endpoint declares with AllowAnonymous attribute
    if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
    {
        //do your stuff...
    }
    await next.Invoke();
});
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
});

关于asp.net-core - 如何从 ASP.Net Core 5 (Razor) 中的中间件获取页面模型的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69096197/

相关文章:

asp.net - 在本地解析Docker主机名时HttpClient花费太多时间

asp.net-mvc - 如何将 Azure Active Directory 身份验证添加到 Razor Pages 应用程序?

c# - 为什么我的列表不在帖子之间维护 PageModel 上的状态?

c# - 如何在 cshtml View 中使用 Asp .NET Core MVC 中的变量?

c# - 更改控制台应用程序图标(Visual Studio代码)

.net - 如何使.NET 5上的ASP.NET Core Web API在Azure上运行?

c# - 在 .NET Core 中注入(inject)通用接口(interface)

c# - 无法执行 Cookie 身份验证 : SignInAsync and AuthenticateAsync not successful

c# - 如何在 NPoco 中获取插入数据的 ID?

c# - 有没有办法以相应的形式显示错误?