如何从 ASP.Net Core 5 (Razor) 中的中间件获取页面模型的类型?
How can I get the Page Model's type from a Middleware in ASP.Net Core 5 (Razor)?
我正在尝试编写一个仅适用于模型 class 上没有 [AllowAnonymous]
属性的 Razor 页面的中间件。但是,要实现这一点,我必须通过 HttpContext
对象以某种方式从中间件中找出页面模型的类型。我不确定这种类型信息是否存在,因为 Razor 页面之前的中间件 运行,所以端点可能还没有从路径中解析出来。
我试过查看 context.Features.Get<IEndpointFeature>()?.Endpoint
class,但我没能找到任何关于端点类型的有用信息。
我也考虑过过滤器,但我正在修改一个现有项目,该项目使用中间件实现了许多检查,如果可以的话,我想避免将它们重写为 IActionFilter
s。
您可以像下面这样使用中间件:
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();
});
我正在尝试编写一个仅适用于模型 class 上没有 [AllowAnonymous]
属性的 Razor 页面的中间件。但是,要实现这一点,我必须通过 HttpContext
对象以某种方式从中间件中找出页面模型的类型。我不确定这种类型信息是否存在,因为 Razor 页面之前的中间件 运行,所以端点可能还没有从路径中解析出来。
我试过查看 context.Features.Get<IEndpointFeature>()?.Endpoint
class,但我没能找到任何关于端点类型的有用信息。
我也考虑过过滤器,但我正在修改一个现有项目,该项目使用中间件实现了许多检查,如果可以的话,我想避免将它们重写为 IActionFilter
s。
您可以像下面这样使用中间件:
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();
});