2014-02-20 211 views
3

我有一个ASP.NET应用程序中使用的Web API 2.POST请求

要强制所有动作模型验证,我使用一个过滤器,像这样:

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请求时,就好像模型验证没有启动。

控制器操作需要viewmodel三个属性 - 所有必需的字符串。

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

如果我只是添加一些随机数据作为请求体,模型验证踢,拒绝该请求符合市场预期,但如果请求体完全是空的,模型验证通和模式,我在我的行动得到一片空白。

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

+0

显示您的模型的代码 –

+2

@SergeyLitvinov完成! –

+0

刚刚发现[这个SO问题](http://stackoverflow.com/questions/19851352/mvc5-webapi2-modelstate-is-valid-with-null-model)处理完全相同的问题,所以我投票关闭这个问题。 –

回答

2

我最终做的是扩展我的模型验证过滤器,以验证模型不为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"); 
     } 
    } 
}