【问题标题】:Remove nulls from IActionResult responses从 IActionResult 响应中删除空值
【发布时间】:2020-09-29 16:56:09
【问题描述】:

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

例子:

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);
}

返回:

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

在上面的示例中,我希望lastName 不在响应中返回。

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

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

但我不想装饰每个班级。

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

services.AddMvcCore().AddNewtonsoftJson(jsonOptions =>
{
    jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

【问题讨论】:

  • @J.Bergmann 这看起来像我需要的,但我在运行时收到此错误Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

标签: c# azure json.net azure-functions


【解决方案1】:

使用 JsonIgnore 属性,如果您无法返回 LastName 属性作为响应:

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

如果该属性的值为 null,则不返回属性作为响应:

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

全局设置方式: 在 Startup.cs 中,可以在 ConfigureServices 方法中附加 JsonOptions(Asp.net Core 3.+):

services.AddControllers().AddJsonOptions(options => {
     options.JsonSerializerOptions.IgnoreNullValues = true;
});

【讨论】:

  • 抱歉,您没有阅读问题。我想要一种全局的方式来做到这一点,而不是每个属性/类。
  • @chris 请看这个链接:forums.asp.net/t/…
【解决方案2】:

其实和web api里面的设置差不多。

在azure函数中,可以使用Dependency Injection,然后注册services.AddMvcCore().AddNewtonsoftJson(xxx)。 DI in azure function,可以参考this article

首先,请确保您已安装以下 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" />

然后在您的 azure 函数项目中,创建一个名为 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;
            });
        }
    }
}

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

【讨论】:

  • 我实际上最终发现了如何做到这一点,这个答案完美地描述了它,因此将标记为已接受!谢谢伊万。
猜你喜欢
  • 2018-01-11
  • 2015-10-16
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多