【问题标题】:How do I use string-ified enum in the body of a POST request to an ASP.NET core server?如何在对 ASP.NET 核心服务器的 POST 请求正文中使用字符串化枚举?
【发布时间】:2021-01-26 11:31:20
【问题描述】:

服务器代码是

[HttpPost("/<route>/update2")]
        public StatusCodeResult UpdatePanel2([FromBody] PanelUpdateReq updateRequest)
        {
            if (updateRequest == null)
                return BadRequest();

            return Ok();
        }
public enum ZZ
    {
        A,
        B
    }

    public class D
    {
        public int Index { get; set; }

        public string Path1 { get; set; }

        public string Path2 { get; set; }

        public ZZ DefectType { get; set; }

        public double foo { get; set; }

        public int bar { get; set; }
    }

    public class PanelUpdateReq
    {
        public int Number { get; set; }

        public string Path { get; set; }

        public List<D> Items { get; set; }
    }

我发现当我为 DefectType 枚举使用数字值(即“DefectType”:0)时,请求返回 OK。但如果我发送字母 "DefectType": "A" 则服务器无法解析请求并返回错误请求。

这是完整的请求:

{
    "Number" : 2738,
    "Path" : "abc/cd/2738",
    "Items": [
        {
            "Index" : 1,
            "Path1" : "some path 1",
            "Path2" : "some path 2",
            "DefectType" : 0, // or "A" which does not work
            "foo": 10.0,
            "bar" : 11
        }
    ]
}

知道这里出了什么问题吗?我在 SO (here's 1 for example) 上查看了多个其他问题,一致认为使用“A”应该可以。

我正在使用 Postman 客户端,如果重要的话,在标题中将内容类型设置为 application/json。

【问题讨论】:

  • 我试过你的代码,它可能没有任何问题
  • 有趣,不适合我
  • 请分享回复

标签: asp.net-mvc asp.net-core


【解决方案1】:

如果给枚举传递字符串,可以在启动时配置枚举的序列化。

services.AddControllers()
            .AddJsonOptions(option=>
            {
                option.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

然后,它可以接收该值。

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2023-03-23
    相关资源
    最近更新 更多