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

馋奶兔 提交于 2019-12-01 05:19: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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!