Web API – Resource Filter

By | 03/11/2021

In this post, we will see how to create Resource Filter in a .NET 5 Web API project.
First of all, what is a Resource Filter?
“A Resource filter is the first to handle a request after authorization. It can run code before the rest of the filter pipeline, and after the rest of the pipeline has completed.
It runs before model binding, so it can influence model binding”.

For all information: Microsoft Web Site.

We take the project used in the post Web API – Action Filter where we will add a new version of the method New Document called NewDocument2:

[HttpPost]
[Route("/v3/document")]
public IActionResult NewDocument2(Document inputDocument)
{
   try
   {
       _documentControllerService.InsertDocument(inputDocument);
       return Ok();
   }
   catch
   {
       return BadRequest();
   }
}



We can see that it is exactly as NewDocument in fact, if we try to run both methods, these will be the results:

LIST

METHOD V1

METHOD V3

CHECK

Now, using a Resource Filter, we will disable the method NewDocument.
First of all, we create a new Class called DisabledV1Filter and we implement OnResourceExecuting method of IResourceFilter interface:

[DISABLEDV1FILTER.CS]

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace CustomDataAnnotaion_Post.Domain.ResourceFilter
{
    public class DisabledV1Filter : Attribute, IResourceFilter
    {
        public void OnResourceExecuted(ResourceExecutedContext context)
        {

        }

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            // We check if V1 is present in the request Path
            if(context.HttpContext.Request.Path.Value.ToUpper().Contains("V1"))
            {
                // We create a Bad Request Result
                context.Result = new BadRequestObjectResult(
                        new
                        {
                            Versioning = new[] { "This version is Expired" }
                        }
                    );
            }
        }
    }
}



Then, we add this new Filter at NewDocument method:

[HttpPost]
[Route("/v1/document")]
[DisabledV1Filter]
public IActionResult NewDocument(Document inputDocument)
{
   try
   {
       _documentControllerService.InsertDocument(inputDocument);
       return Ok();
   }
   catch
   {
       return BadRequest();
   }
}



We have done and now, if we try to call the two methods, these will be the results:

LIST

METHOD V3

METHOD V1

LIST FOR CHECK




Leave a Reply

Your email address will not be published. Required fields are marked *