Tuesday, 14 July 2026

Apply Filter Dynamically on WebApi Controller based on Header Value and modify the response in Filter

 In this post we are going to see how to apply filter on web api controller based on the api version which is passed on http request header. we will pass a header key "version" which may contain value "v1" or "v2". if we get the value as "v1" we will apply version 1 Filter for others different version filter. First we will see the Filters sample.

ApiV1Filter

  internal class ApiV1Filter : Attribute, IActionFilter
  {
      public void OnActionExecuted(ActionExecutedContext context)
      {
          var res = context.Result;

          if (res is ObjectResult jsonData)
          {

              string data = JsonConvert.SerializeObject(jsonData.Value);

              JObject jsonPayload = new JObject();

              jsonPayload["data"] = JArray.Parse(data);
              jsonPayload.Add(new JProperty("version", "v1"));

              context.Result = new Microsoft.AspNetCore.Mvc.ContentResult
              {
                  Content = jsonPayload.ToString(),
                  ContentType = "application/json",
                  StatusCode = 200
              };
          }
      }

      public void OnActionExecuting(ActionExecutingContext context)
      {
         Console.WriteLine("ApiV1Filter: Action executing.");
      }
  }


ApiV2Filter
internal class ApiV2Filter : Attribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { var res = context.Result; if (res is ObjectResult jsonData) { string data = JsonConvert.SerializeObject(jsonData.Value); JObject jsonPayload = new JObject(); jsonPayload["data"] = JArray.Parse(data); jsonPayload.Add(new JProperty("version", "v2")); context.Result = new Microsoft.AspNetCore.Mvc.ContentResult { Content = jsonPayload.ToString(), ContentType = "application/json", StatusCode = 200 }; } } public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("ApiV2Filter: Action executing."); } }

FilterFactory

internal class VersionFilterFactory : Attribute, IFilterFactory { public bool IsReusable => false; public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { if (serviceProvider != null) { var http = serviceProvider.GetService<IHttpContextAccessor>(); var version = http.HttpContext.Request.Headers["version"]; if (version == "v1") { return serviceProvider.GetService<ApiV1Filter>(); } return serviceProvider.GetService<ApiV2Filter>(); } throw new InvalidOperationException("Service provider is null."); } }

In the above code we have two filters in FilterFactory we are applying one filter dynamically to the Controller based on header version. Next step is register the filters in program.cs and apply it on controller.

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ApiV1Filter>();
builder.Services.AddScoped<ApiV2Filter>();

When you give request with header V1 or with out header we will get different response for testing purpose i am returing json with custom property version with value v1 or v2. you can see below.




From this post you can learn the applying filter dynamically to controller using IFilterFactory