从 IActionResult 响应中删除空值

chr*_*ris 7 c# azure json.net azure-functions

我想设置一个全局设置,以便null在从我的任何 HTTP 函数返回的任何响应中不返回属性。

例子:

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);
}
Run Code Online (Sandbox Code Playgroud)

返回:

{
    "id": 1,
    "firstName": "Chris",
    "lastName": null
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我不想lastName在响应中返回。

我知道您可以执行以下操作:

{
    "id": 1,
    "firstName": "Chris",
    "lastName": null
}
Run Code Online (Sandbox Code Playgroud)

但我不想装饰每个班级。

在 Web API 中,在Startup.cs文件中,您可以执行以下操作:

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

Iva*_*ang 3

实际上,它与 web api 中的设置几乎相同。

在azure函数中,您可以使用Dependency Injection,然后注册services.AddMvcCore().AddNewtonsoftJson(xxx)。关于azure函数中的DI,可以参考这篇文章

首先,请确保您安装了以下 nuget 软件包(我在本测试中使用的是 azure function v3):

<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" />
Run Code Online (Sandbox Code Playgroud)

然后在您的 azure function 项目中,创建一个名为 的类Startup.cs。这是这个类的代码:

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;
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后运行你的azure函数,空值将被删除。下面是测试结果的截图:

在此输入图像描述