Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for an attribute in an action filter

In MVC 5, you can do something like this inside an IActionFilter, to check if an attribute has been declared on the the current action (or at controller scope)

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    // Stolen from System.Web.Mvc.AuthorizeAttribute
    var isAttributeDefined = filterContext.ActionDescriptor.IsDefined(typeof(CustomAttribute), true) ||
                             filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(CustomAttribute), true);

}

So if your controller defines the attribute like so, this works.

[CustomAttribute]
public ActionResult Everything()
{ .. }

Is it possible to do the same in ASP.NET Core MVC (inside an IActionFiler)?

like image 409
Matt Roberts Avatar asked May 26 '17 10:05

Matt Roberts


People also ask

How do you unit test an action filter?

To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those).

What is action filter attribute in MVC?

The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called.

What is filter attribute?

An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed.

What is the order in which the action filters are executed?

Filters execute in this order: Authorization filters. Action filters. Response/Result filters.


Video Answer


1 Answers

Yes you can do it. Here is similar code for ASP.NET Core.

public void OnActionExecuting(ActionExecutingContext context)
{
    var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
    if (controllerActionDescriptor != null)
    {
        var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
            .Any(a => a.GetType().Equals(typeof(CustomAttribute)));
    }
}
like image 53
Anuraj Avatar answered Sep 18 '22 09:09

Anuraj