Sha*_*awn 33 c# asp.net-core-webapi asp.net-core-3.0 .net-core-3.0
我最近将我的 web api 从 .Net core 2.2 升级到 .Net core 3.0,并注意到当我将帖子中的枚举传递给我的端点时,我的请求现在出现错误。例如:
我的 api 端点有以下模型:
public class SendFeedbackRequest
{
public FeedbackType Type { get; set; }
public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
反馈类型如下所示:
public enum FeedbackType
{
Comment,
Question
}
Run Code Online (Sandbox Code Playgroud)
这是控制器方法:
[HttpPost]
public async Task<IActionResult> SendFeedbackAsync([FromBody]SendFeedbackRequest request)
{
var response = await _feedbackService.SendFeedbackAsync(request);
return Ok(response);
}
Run Code Online (Sandbox Code Playgroud)
我将它作为帖子正文发送给控制器的地方:
{
message: "Test"
type: "comment"
}
Run Code Online (Sandbox Code Playgroud)
我现在收到以下错误发布到此端点:
The JSON value could not be converted to MyApp.Feedback.Enums.FeedbackType. Path: $.type | LineNumber: 0 | BytePositionInLine: 13."
这在 2.2 中有效,并在 3.0 中开始出现错误。我看到关于 json 序列化器在 3.0 中发生变化的讨论,但不确定应该如何处理。
Pas*_*hec 54
对于那些正在寻找片段的人
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
}
Run Code Online (Sandbox Code Playgroud)
Nko*_*osi 31
从 3.0 版本开始,.NET Core 不再Newtonsoft.Json默认使用第三方(Json.NET),而是使用新的内置System.Text.Json(STJ) 序列化程序——它不像 Json.NET 那样功能丰富,当然还有它自己的问题和学习曲线以获得预期的功能。
如果您想切换回使用的先前默认值Newtonsoft.Json,则必须执行以下操作:
安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。
在ConfigureServices()添加呼叫AddNewtonsoftJson()
public void ConfigureServices(IServiceCollection services) {
//...
services.AddControllers()
.AddNewtonsoftJson(); //<--
//...
}
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您使用内置的 JsonStringEnumConverter 并将其传递给 JsonSerializerOptions,则支持将枚举序列化为字符串已经存在:https ://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonstringenumconverter ?view=netcore-3.0
这是使用它的示例测试:https : //github.com/dotnet/corefx/blob/master/src/System.Text.Json/tests/Serialization/ReadScenarioTests.cs#L17
| 归档时间: |
|
| 查看次数: |
10177 次 |
| 最近记录: |