ASP.Net 5 MVC 6 - how to return invalid JSON message on POST using FromBody?

后端 未结 2 769
自闭症患者
自闭症患者 2021-01-12 09:40

I am creating an ASP.Net 5 application with MVC 6, using .Net 4.5.1. I have a POST method that uses a FromBody parameter to get the object automatically.

[Ht         


        
2条回答
  •  梦谈多话
    2021-01-12 10:17

    The default JsonInputFormatter will in fact return a null model upon encountering an error - but it will populate ModelState with all exceptions.

    So you have access to all encountered errors by digging into ModelState:

    [HttpPost]
    public IActionResult Insert([FromBody]Agent agent)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState
                .SelectMany(x => x.Value.Errors, (y, z) => z.Exception.Message);
    
            return BadRequest(errors);
        }
    
        // Model is valid, do stuff.
    }
    

    Output of above is an array of all exception messages, e.g.:

    [
        "After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20",
        "Another exception message..."
    ]
    

    JsonInputFormatter - Source

提交回复
热议问题