Question

I have an ASP.NET application using Web API 2.

To force model validation on all actions, I use a filter, like so:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

This works well in most cases, but when I execute a POST request against an API-endpoint without any content in the request body, it is as if the model validation does not kick in.

The controller-action takes a viewmodel with three properties - all required strings.

public class AddEntityViewModel
{
    [Required]
    public string Property1 { get; set; }
    [Required]
    public string Property2 { get; set; }
    [Required]
    public string Property3 { get; set; }
}

If I just add some random data as the request body, model validation kick in and deny the request as expected, but if the request body is completely empty, model validation pass and the model I get in my action is null.

Is there a good way to force model validation even if the request body is empty, so that such requests are denied? Or is there some other way to approach this?

Was it helpful?

Solution

What I ended up doing was extending my model validation filter to also verify that the model isn't null.

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        } 
        else if (actionContext.ActionArguments.ContainsValue(null))              
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, "Request body cannot be empty");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top