枚举类型不再在.Net Core 3.0 FromBody请求对象中工作 [英] Enum type no longer working in .Net core 3.0 FromBody request object

查看:490
本文介绍了枚举类型不再在.Net Core 3.0 FromBody请求对象中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have recently upgraded my web api from .Net core 2.2 to .Net core 3.0 and noticed that my requests are getting an error now when I pass an enum in a post to my endpoint. For example:

我的api端点具有以下模型:

I have the following model for my api endpoint:

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

其中的FeedbackType如下:

Where the FeedbackType looks like so:

    public enum FeedbackType
    {
        Comment,
        Question
    }

这是控制器方法:

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

        return Ok(response);
    }

我将其作为发布正文发送给控制器的地方:

Where I send this as the post body to the controller:

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

我现在在此端点上发布以下错误:

And I am now getting the following error posting to this endpoint:

JSON值无法转换为MyApp.Feedback.Enums.FeedbackType。路径:$。type |行号:0 | BytePositionInLine:13

这在2.2版本中有效,并在3.0版中启动了错误。我看到了关于JSON序列化程序在3.0版中发生变化的讨论,

This was working in 2.2 and started the error in 3.0. I saw talk about the json serializer changing in 3.0, but not sure how this should be handled.

推荐答案

框架默认不再使用Json.Net和新的内置序列化程序

framework no longer uses Json.Net by default and the new built-in serializer has its own issues and learning curve to get the expected features.

如果要切换回以前使用 Newtonsoft的默认设置,则有其自身的问题和学习曲线。 Json ,那么您必须执行以下操作:

If you’d like to switch back to the previous default of using Newtonsoft.Json, then you'll have to do the following:


  1. 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet软件包。

  1. Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package.

ConfigureServices()中添加对 AddNewtonsoftJson()



public void ConfigureServices(IServiceCollection services) {
    //...

    services.AddControllers()
        .AddNewtonsoftJson(); //<--

    //...
}

这篇关于枚举类型不再在.Net Core 3.0 FromBody请求对象中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆