如何从HttpContext获取ASP.NET Core MVC筛选器

Muh*_*eed 4 c# httpcontext asp.net-core-mvc asp.net-core asp.net-core-middleware

我正在尝试编写一些中间件,并且需要知道当前的操作方法(如果有)是否具有特定的过滤器属性,因此我可以根据其存在来更改行为。

因此,是否有可能IList<IFilterMetadata>像在ResourceExecutingContext实现a时所做的那样获取类型的过滤器集合IResourceFilter

dav*_*owl 6

今天真的不可能。

在ASP.NET Core 3.0中可能

app.UseRouting();


app.Use(async (context, next) =>
{
    Endpoint endpoint = context.GetEndpoint();

    YourFilterAttribute filter = endpoint.Metadata.GetMetadata<YourFilterAttribute>();

    if (filter != null)
    { 

    }

    await next();
});


app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)


Kah*_*azi 5

ASP.NET Core 3.0 使用新的路由,每个操作都是 ,Endpoint并且操作和控制器上的所有属性都存在于Metadata

以下是您可以如何做到这一点。

app.UseRouting();


app.Use(async (context, next) =>
{
    Endpoint endpoint = context.GetEndpoint();

    YourFilterAttribute filter = endpoint.Metadata.GetMetadata<YourFilterAttribute>();

    if (filter != null)
    { 

    }

    await next();
});


app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)

  • 这与上一篇文章中的代码完全相同(您编辑以包含该代码),因此现在是重复的答案 (2认同)