gpt4 book ai didi

c# - 枚举类型不再在 .Net core 3.0 FromBody 请求对象中工作

转载 作者:行者123 更新时间:2023-12-02 09:05:49 24 4
gpt4 key购买 nike

我最近将我的 Web api 从 .Net core 2.2 升级到 .Net core 3.0,并注意到当我将帖子中的枚举传递到我的端点时,我的请求现在出现错误。例如:

我的 api 端点有以下模型:

public class SendFeedbackRequest
{
public FeedbackType Type { get; set; }
public string Message { get; set; }
}

FeedbackType 如下所示:

public enum FeedbackType
{
Comment,
Question
}

这是 Controller 方法:

[HttpPost]
public async Task<IActionResult> SendFeedbackAsync([FromBody]SendFeedbackRequest request)
{
var response = await _feedbackService.SendFeedbackAsync(request);

return Ok(response);
}

我将其作为帖子正文发送到 Controller :

{
message: "Test"
type: "comment"
}

我现在在发布到此端点时收到以下错误:

JSON 值无法转换为 MyApp.Feedback.Enums.FeedbackType。路径:$.type |行号: 0 |字节位置内联:13。”

这在 2.2 中有效,但在 3.0 中开始出现错误。我看到有关 json 序列化器在 3.0 中发生变化的讨论,但不确定应该如何处理。

最佳答案

对于那些在使用System.Text.Json时寻找片段的人

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
}

.NET 6/Top-level statement style

using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers()
//convert strings to enums
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters
.Add(new JsonStringEnumConverter()));

关于c# - 枚举类型不再在 .Net core 3.0 FromBody 请求对象中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440400/

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