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

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

提交回复
热议问题