没有内容的POST请求传递模型验证

时间:2014-02-20 10:33:48

标签: c# asp.net asp.net-web-api model-validation

我有一个使用Web API 2的ASP.NET应用程序。

要对所有操作强制进行模型验证,我使用过滤器,如下所示:

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

这在大多数情况下效果很好,但是当我对API端点执行POST请求而请求正文中没有任何内容时,就好像模型验证没有启动一样。

controller-action采用具有三个属性的viewmodel - 所有必需的字符串。

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

如果我只是添加一些随机数据作为请求体,模型验证会按预期启动并拒绝请求,但如果请求体完全为空,则模型验证通过,我在我的操作中获得的模型为空。< / p>

即使请求正文为空,是否有强制模型验证的好方法,以便拒绝此类请求?或者还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

我最终做的是扩展我的模型验证过滤器以验证模型不为空。

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");
        }
    }
}
相关问题