Concrete filter implementations

In general, filters can be implemented by extending the built-in types provided by ASP.NET Core. Let's walk through a simple declaration of a custom action filter:

using Microsoft.AspNetCore.Mvc.Filters;

namespace SampleAPI.Filters
{
public class CustomActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// do something before the action executes
}

public void OnActionExecuted(ActionExecutedContext context)
{
// do something after the action executes
}
}
}

The CustomActionFilter class implements the IActionFilter interface type, which offers two different methods:

  • The OnActionExecuting method is triggered before the execution of the action.
  • The OnActionExecuted method is executed after the action.

Both methods receive the execution context as a callback parameter, which provides some useful information about the filter's stack metadata, the controllers, the action arguments, and route data. Furthermore, the context parameter also provides access to the HttpContext attribute we looked at in previous chapters. The HttpContext provides all the necessary properties so that we can access dependency injection services and the request/response data. ASP.NET Core heavily uses the asynchronous stack. This means it also provides an interface that we can use to implement asynchronous filters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.175.182