What are the different types of filters in C# ASP.NET WebAPI?

CsharpServer Side ProgrammingProgramming

Filters are used to inject extra logic at the different levels of WebApi Framework request processing. Filters provide a way for cross-cutting concerns (logging, authorization, and caching). Filters can be applied to an action method or controller in a declarative or programmatic way. Below are the types of filters in Web API C#.

Authentication Filter

An authentication filter helps us to authenticate the user detail. In the authentication filter, we write the logic for checking user authenticity.

Authorization Filter

Authorization Filters are responsible for checking User Access. They implement the IAuthorizationFilterinterface in the framework.

Action Filter

Action filters are used to add extra logic before or after action methods execution. The OnActionExecuting and OnActionExecuted methods are used to add our logic before and after an action method is executed.

Exception Filter

An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.

Override Filter

Override filters are used to customize the behaviour of other filter for individual action method. Sometimes there is a requirement like whatever the filters we are having we need to override. Let us say we applied the filter at the controller level but there is an action within a controller where we don’t want to use the filter so we can use the override version of the filter.

Filters are generally applied in below of three ways.

  • At Controller level

  • At ActionMethod level

  • At Global level (WebApi.Config.cs)

Let us see an example of implementation of an authorization filter and how it works.

Example

using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [Authorize]
      public IHttpActionResult Get(){
         return Ok();
      }
   }
}

Since we have added the authorize attribute over the action method, proper authorization like bearer token, API key, OAuth etc., should be used to access the action method. Unauthorized access will result in 401 Unauthorized response which is shown below.


raja
Published on 19-Aug-2020 11:58:46
Advertisements