C# 枚举类型不再在.Net core 3.0 FromBody请求对象中工作
我最近将我的web api从.Net core 2.2升级到了.Net core 3.0,并注意到现在当我将post中的枚举传递到我的端点时,我的请求出现了错误。例如: 我的api端点有以下模型:C# 枚举类型不再在.Net core 3.0 FromBody请求对象中工作,c#,asp.net-core-webapi,asp.net-core-3.0,.net-core-3.0,C#,Asp.net Core Webapi,Asp.net Core 3.0,.net Core 3.0,我最近将我的web api从.Net core 2.2升级到了.Net core 3.0,并注意到现在当我将post中的枚举传递到我的端点时,我的请求出现了错误。例如: 我的api端点有以下模型: public class SendFeedbackRequest { public FeedbackType Type { get; set; } public string Message { get; set; } } 反馈类型如下所示:
public class SendFeedbackRequest
{
public FeedbackType Type { get; set; }
public string Message { get; set; }
}
反馈类型如下所示:
public enum FeedbackType
{
Comment,
Question
}
这是控制器方法:
[HttpPost]
public async Task<IActionResult> SendFeedbackAsync([FromBody]SendFeedbackRequest request)
{
var response = await _feedbackService.SendFeedbackAsync(request);
return Ok(response);
}
现在,我在该端点上收到以下错误信息:
public class SendFeedbackRequest
{
public FeedbackType Type { get; set; }
public string Message { get; set; }
}
无法将JSON值转换为MyApp.Feedback.Enums.FeedbackType。路径:$。键入|行号:0 |字节位置行:13。“
这在2.2中起作用,并在3.0中引发了错误。我看到了关于json序列化程序在3.0中发生更改的讨论,但不确定应该如何处理。如果使用内置JsonStringEnumConverter并将其传递到JsonSerializerOptions中,则已经存在对将枚举序列化为字符串的支持: 下面是一个使用它的示例测试:
从3.0版开始,.NET Core默认情况下不再使用第三方
Newtonsoft.Json
(Json.NET),而是使用新的内置System.Text.Json
(STJ)序列化程序,它的功能不如Json.NET丰富,当然也有自己的问题和学习曲线来获得预期的功能
如果您想切换回以前默认使用的Newtonsoft.Json
,则必须执行以下操作:
ConfigureServices()
中添加对AddNewtonsoftJson()的调用
public void配置服务(IServiceCollection服务){
//...
services.AddControllers()
.AddNewtonsoftJson();//用于查找代码段的用户
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
}
我想指出这两个步骤都必须采取。这是很明显的,但是如果您忘记了Nuget包,只添加了“AddNewtonsoftJson()”,那么您的代码编译和运行很好,但它不起作用。对于那些不知道如何将JSonStringUnimConverter传递到JsonSerialzerOptions的人,下面是代码:services.AddMvc().AddJsonOptions(options=>{options.JsonSerializerOptions.Converters.Add(新的JSONStringGenumConverter());options.JsonSerializerOptions.IgnoreNullValues=true;});
它应该是StringEnumConverter
,而不是JsonStringEnumConverter
@villecoder JsonStringEnumConverter是正确的,除非您使用的是来自newtonsoft的json,但也应该使用JsonSerializerSettings,而不是JSONSerializerConverter。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
}