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

后端 未结 2 742
自闭症患者
自闭症患者 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:16

    I found myself with exactly the same problem, but was able to find a different solution. I will share my solution here as an alternative to @ypsilo0n's answer.

    Instead of checking in every controller the if (!ModelState.IsValid) we can have this middleware filter:

    public class FooFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
    
            if (modelState != null && modelState.IsValid == false)
            {
                // this class takes the model state and parses 
                // it into a dictionary with all the errors
                var errorModel = new SerializableError(modelState);
    
                context.Result = new BadRequestObjectResult(errorModel);
            }
        }
    }
    

    Now, the controller never gets called because this middleware runs before and ends the request. (read docs for more information).

    When we set a non-null context.Result it means "end the HTTP request here" (the docs) -- not very user friendly/intuitive if you ask me but OK (would expect a return value instead).


    using .net core 1.1

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题