Async OnActionExecuting in ASP.NET Core’s ActionFilterAttribute

Asynchronous filters work a bit differently: first execute code that must be executed before the action, call next() for the actual logic, finally add code to be executed after the action. public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // logic before action goes here await next(); // the actual action // logic after the … Read more

Order of execution with multiple filters in web api

Some things to note here: Filters get executed in the following order for an action: Globally Defined Filters -> Controller-specific Filters -> Action-specific Filters. Authorization Filters -> Action Filters -> Exception Filters Now the problem that you seem to mention is related to having multiple filters of the same kind (ex: Multiple ActionFilterAttribute decorated on … Read more

Extend AuthorizeAttribute Override AuthorizeCore or OnAuthorization

The clue is in the return types: AuthorizeCore returns a boolean – it is decision making code. This should be limited to looking at the user’s identity and testing which roles they are in etc. etc. Basically it should answer the question: Do I want this user to proceed? It should not perform any additional … Read more

How can you unit test an Action Filter in ASP.NET Web Api?

You can create a fake for HttpActionExecutedContext as below: public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null) { HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext(); HttpActionDescriptor descriptor = actionDescriptor ?? new Mock<HttpActionDescriptor>() { CallBase = true }.Object; return new HttpActionContext(context, descriptor); } public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response) { HttpActionContext actionContext = … Read more

In what order are filters executed in asp.net mvc

Filters run in the following order: Authorization filters Action filters Response filters Exception filters For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the … Read more