c# - 从 IActionResult 响应中删除空值

标签 c# azure json.net azure-functions

我想设置一个全局设置,以便在从任何 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;
});

最佳答案

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

在azure函数中,您可以使用依赖注入(inject),然后注册services.AddMvcCore().AddNewtonsoftJson(xxx)。 azure函数中的DI可以引用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 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;
            });
        }
    }
}

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

enter image description here

关于c# - 从 IActionResult 响应中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62300816/

相关文章:

c# - System.IO.Directory.Exists() 与 Windows 和 Linux 一起使用

c# - 回发后 ViewState 变量重置

azure - 获取Azure订阅ID和部署槽(非常快)

c# - 如何最大程度地减少大型数据集的运行时间(从 93,773 个对象列表中列出唯一对象)

c# - 我可以配置 ServiceStack.Text 以将枚举值序列化为驼峰命名法吗?

c# - 从结构化数据构建 JSON 层次结构

c# - 获取有关 USB 串口转换器的信息

c# - 为什么对象在 IIS7 中从我的 session 中消失?

azure - 是否可以在 Azure DevOps 上升级到性能更高的 Microsoft 托管构建代理?

c# - Graph API - 使用 .Net Core 3.1 添加架构扩展