Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ASP.NET Core MVC Filters from HttpContext

I'm trying to write some middleware and need to know if the current action method (if any) has a particular filter attribute, so I can change behaviour based it's existence.

So is it possible to get a filters collection of type IList<IFilterMetadata> like you do on the ResourceExecutingContext when you are implementing an IResourceFilter?

like image 715
Muhammad Rehan Saeed Avatar asked Sep 05 '17 16:09

Muhammad Rehan Saeed


People also ask

How do I get HttpContext in .NET Core?

In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.

How do I find HttpContext current?

HttpContext parameter in middleware If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }

How do I use filters in NET Core Web API?

Filters in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline. Built-in filters handle tasks such as: Authorization, preventing access to resources a user isn't authorized for. Response caching, short-circuiting the request pipeline to return a cached response.

What is HttpContext MVC?

ASP.NET MVC 5 for Beginners The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.


1 Answers

It's not really possible today.

It is possible in 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();
});
like image 144
davidfowl Avatar answered Sep 28 '22 02:09

davidfowl