gpt4 book ai didi

c# - 当值类型可为空时,为什么 ApiController 返回空字典?

转载 作者:行者123 更新时间:2023-11-30 12:19:24 24 4
gpt4 key购买 nike

考虑这个 Controller :

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
[HttpGet]
public Dictionary<string, int?> Get()
{
return new Dictionary<string, int?>()
{
{"foo", null},
{"bar", 1}
};
}
}
}

当我通过 /example 访问这个 Controller 时,我收到的响应仅包含 {} .控制台中没有错误或警告。

但是,如果我删除 ?int之后签名(即将可为空的整数更改为不可为空的整数)并替换 null0 ,它会按原样返回 Dictionary。 decimal 会出现此问题, boolchar ,也是。

应该注意的是,并非所有可为空的类型都以这种方式表现。例如,string工作得很好。

编辑 Controller :

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
[HttpGet]
public Dictionary<string, int> Get()
{
return new Dictionary<string, int>()
{
{"foo", 0},
{"bar", 1}
};
}
}
}

响应:

{"foo":0,"bar":1}

返回类型如 int?List<int?>按预期工作,只有字典有问题。

为什么会这样?是谁的错?

我正在使用 .NET Core SDK (3.0.100) , 目标框架是 netcoreapp3.0 .我使用 JetBrains Rider 的 GUI(File -> New... -> ASP.NET Core Web Application -> 类型:Web API)创建了这个 WebApplication。

最佳答案

我在 ASP.Net Core 2.2 中尝试了您的代码,它的工作让我相信这是新的 Microsoft JSON 序列化程序的问题,它应该取代以前使用的 Newtonsoft 序列化程序。

我通过安装旧的 Newtonsoft 解决了这个问题:

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.0.0

并这样使用它:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}

只需将 AddNewtonsoftJson 添加到您的配置中。该方法允许您像往常一样设置 JSON 序列化程序,尽管我还没有修改它。

希望这对您有所帮助。

关于c# - 当值类型可为空时,为什么 ApiController 返回空字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com