Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nulls from IActionResult responses

I would like to set a global setting for not returning null properties in any response returned from any of my HTTP functions.

Example:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[FunctionName("HttpTriggeredFunction")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
    ILogger log)
{
    var user = new User
    {
        Id = 1,
        FirstName = "Chris",
        LastName = null
    };

    return new OkObjectResult(user);
}

returns:

{
    "id": 1,
    "firstName": "Chris",
    "lastName": null
}

In the above example, I want lastName to not be returned in the response.

I'm aware you can do things like:

[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

but I don't want to have to decorate every class.

In Web API, in the Startup.cs file, you could do something like this:

services.AddMvcCore().AddNewtonsoftJson(jsonOptions =>
{
    jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
like image 311
Chris B Avatar asked Jun 10 '20 10:06

Chris B


2 Answers

Actually, it's almost the same settings as it's in web api.

In azure function, you can use Dependency Injection, and then register services.AddMvcCore().AddNewtonsoftJson(xxx). For DI in azure function, you can refer to this article.

First, please make sure you have the following nuget packages installed(I'm using azure function v3 in this test):

<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.5" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />

Then in your azure function project, create a class named Startup.cs. Here is the code of this class:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

//add this line of code here.
[assembly: FunctionsStartup(typeof(FunctionApp6.Startup))]
namespace FunctionApp6
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddMvcCore().AddNewtonsoftJson(jsonOptions =>
            {
                jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });
        }
    }
}

Then run your azure function, the null value will be removed. Here is the screenshot of the test result:

enter image description here

like image 59
Ivan Yang Avatar answered Oct 25 '22 21:10

Ivan Yang


Use JsonIgnore Attribute,if you can't return LastName Property in response:

[JsonIgnore]
 public string LastName { get; set; }

if value of that property is null, don't return property in response:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
 public string LastName { get; set; }

global setting way: In Startup.cs, you can attach JsonOptions in ConfigureServices method (Asp.net Core 3.+):

services.AddControllers().AddJsonOptions(options => {
     options.JsonSerializerOptions.IgnoreNullValues = true;
});
like image 41
Amin Golmahalle Avatar answered Oct 25 '22 21:10

Amin Golmahalle