-1

How to create action filter which will remove null values from Response.Content?

Suppress NULL Values in every API call

OnActionExecuted

Want to suppress null values only for one Method

piet.t
  • 11,718
  • 21
  • 43
  • 52
Chenna
  • 2,383
  • 3
  • 20
  • 36

1 Answers1

2

If you use Formatters.JsonFormatter in your WebApiConfig.cs then

1) If you have to ignore null values at application level means for all your api actions

The filter will be

public class IgnoreNullValuesFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.ActionContext.RequestContext.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
        base.OnActionExecuted(actionExecutedContext);
    }
}

And add this filter to your WebApiConfig.cs like

config.Filters.Add(new IgnoreNullValuesFilter());

After adding this filter to you will find all your api actions return data with ignoring null values

You don't need to annotate your api action [IgnoreNullValuesFilter] with this because we added it as globally in WebApiConfig.cs

For point no. 2) and 3) don't add filter in WebApiConfig.cs

2) If you have to ignore null values for specific api actions with action filter

Then filter will be

public class IgnoreNullValuesFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var objectContent = actionExecutedContext.Response.Content as ObjectContent;
        if (objectContent != null)
        {
            var type = objectContent.ObjectType;
            var value = JsonConvert.SerializeObject(objectContent.Value, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            objectContent.Value = value;

            //If you want to send your response as strongly type
            JObject jObject = JObject.Parse(value);
            objectContent.Value = jObject;
        }

        base.OnActionExecuted(actionExecutedContext);
    }
}

And your api for ignore null values

[HttpGet]
[IgnoreNullValuesFilter]
public IHttpActionResult ApiName()
{
    var myObject = new Item { Id = 1, Name = "Matthew", Salary = 25000, Department = null };

    return Ok(myObject);
}

If you want to include null values then just remove [IgnoreNullValuesFilter] from your api

3) If you don't want to use any action filter then

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public long Salary { get; set; }
    public string Department { get; set; }
}

And your API will be look like

[HttpGet]
public IHttpActionResult ApiName()
{
    var myObject = new Item { Id = 1, Name = "Matthew", Salary = 25000, Department = null };

    return Json(myObject, new JsonSerializerSettings()
    {
        NullValueHandling = NullValueHandling.Ignore
    });
}

OR

[HttpGet]
public IHttpActionResult ApiName()
{
    var myObject = new Item1 { Id = 1, Name = "Matthew", Salary = 25000, Department = null };

    var jsonIgnoreNullValues = JsonConvert.SerializeObject(myObject, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
        {
          NullValueHandling = NullValueHandling.Ignore
        });

    JObject jObject = JObject.Parse(jsonIgnoreNullValues);

    return Ok(jObject);
}

Result:

enter image description here

Here you see in response that Item has property department = null ignore by formatter.

You can send myObject as any type of data that you want

er-sho
  • 9,581
  • 2
  • 13
  • 26
  • 1
    @Chenna, view edit section in answer might be it help you :) – er-sho Aug 02 '18 at 14:11
  • Even though filter is supposed to be applied for only one method, this is getting applied to all later API calls once filter method is executed – Chenna Aug 06 '18 at 06:42
  • @chenna, view `Edit: 06-08-2018` section in answer it can ignore null values for specific method without affecting your global `JsonSerilizerSetting` means global `HttpConfiguration` may it help you and accept answer :) – er-sho Aug 06 '18 at 07:13
  • @Chenna, Yes I got it why all your api calls ignore null values, did u add `NullValueHandling = NullValueHandling.Ignore` in your action filter? If yes then remove it otherwise it can ignore null values for all you api calls, If you want to ignore null values for only one or specific calls then use `Edit` section in answer might be it help you – er-sho Aug 06 '18 at 07:27
  • @Chenna,, either you have to set in action filter or in your api method, If you set `NullValueHandling.Ignore` in action filter then i will apply to all, but if you set on api method level then it cant affect to others method, got it? – er-sho Aug 06 '18 at 07:36
  • Thanks for your help, to Suppress globally I can mention config in `WebApiConfig`, but the whole point of question is how to use it as `filter` – Chenna Aug 06 '18 at 07:43
  • @Chenna, finally your problem has been solved with action filter. view Point No `1)` and `2)` in answer might be it help you :) – er-sho Aug 06 '18 at 10:46
  • @Chenna, Have you look on my updated answer? , specilly point no. 1) and 2). Its for only action filter that you want :) – er-sho Aug 28 '18 at 09:02