Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

How do I use string-ified enum in the body of a POST request to an ASP.NET core server?

The server code is

[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; }
    }

I find that when I use a number value for the DefectType enum (i.e. "DefectType": 0), the request returns OK. But if I send the letter "DefectType": "A" then the server cannot parse the request and returns a bad request.

Here's the full request :

{
    "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
        }
    ]
}

Any idea what's going wrong here? I have looked at multiple other questions here on SO (here's 1 for example), and the consensus is that using "A" should work.

I am using Postman client, and content type is set as application/json in the header if that matters.

question from:https://stackoverflow.com/questions/65880028/how-do-i-use-string-ified-enum-in-the-body-of-a-post-request-to-an-asp-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you pass a string to the enum, you can configure the serialization of the enum in the startup.

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

Then, it can receive the value.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...