Brandon Cuff
Brandon Cuff

Reputation: 1478

how to Handle Empty Model Validation in MVC Core?

I have a simple action using ASP NET Core (Not old web api or mvc):

[HttpPost]
public async Task<SomeResponse> Something([FromBody] SomeRequest request)
{
    // request is null here when the POST body is empty
}

When I POST an empty body request is null. I have a global action filter that returns a generic 400 response if there are any model validation errors.

public class ValidateModelBindingAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            // 400 response here.
        }
    }
}

I would like the ModelState to be invalid if the body is empty so that the validation filter will respond with a 400 before attempting to execute the action with a null request object. I tried adding a [Required] attribute to the request parameter to no effect. Is there another solution out there?

Upvotes: 1

Views: 2314

Answers (1)

Usman
Usman

Reputation: 4703

it considers Null model valid because it checks ModelState.ErrorCount in case of null it will be 0 thats why it will consider it as valid model so you can try this

 public class ValidateViewModelAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext actionContext)
            {
                if (actionContext.ActionArguments.Any(x => x.Value == null))
                {
                    actionContext.Result = new BadRequestObjectResult(HttpStatusCode.BadRequest);

                }

                if (actionContext.ModelState.IsValid == false)
                {
                    actionContext.Result = new BadRequestObjectResult(HttpStatusCode.BadRequest);
                }
            }
        }

and dont forget to add the ValidateViewModel attribute on action

Upvotes: 2

Related Questions