7

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;
});
Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
Chris
  • 3,113
  • 5
  • 24
  • 46
  • 1
    Does this answer your question? [.NET Core: Remove null fields from API JSON response](https://stackoverflow.com/questions/44595027/net-core-remove-null-fields-from-api-json-response) – J. Bergmann Jun 10 '20 at 10:07
  • @J.Bergmann that looks like what I need but I get this error at runtime `Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'` – Chris Jun 10 '20 at 10:15

2 Answers2

3

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

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • I actually found out how to do it in the end and this answer describes it perfectly so will mark as accepted! Thanks Ivan. – Chris Jun 11 '20 at 12:07
1

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;
});
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36