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
)?
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).
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.
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.
Filters execute in this order: Authorization filters. Action filters. Response/Result filters.
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)));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With