C# 无内容传递模型验证的POST请求
我有一个使用Web API 2的ASP.NET应用程序 为了强制对所有操作进行模型验证,我使用了一个过滤器,如下所示:C# 无内容传递模型验证的POST请求,c#,asp.net,asp.net-web-api,model-validation,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)
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; }
}
如果我只是添加一些随机数据作为请求主体,那么模型验证将按预期启动并拒绝请求,但是如果请求主体完全为空,那么模型验证将通过,并且我在操作中得到的模型为空
即使请求主体为空,是否有好的方法强制进行模型验证,从而拒绝此类请求?或者有其他方法来实现这一点吗?我最终做的是扩展模型验证过滤器,以验证模型是否为空
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");
}
}
}
显示您的代码model@SergeyLitvinov完成!刚刚发现这个问题处理的是完全相同的问题,所以我投票决定结束这个问题。@Christof Reliasson如果这是你的问题,你能不能删除它?@MichaelEdenfield我可以,但正如前面提到的,重复的问题通常可以作为其他问题上其他有用答案的路标。由于人们倾向于使用完全不同的词提问和搜索,所以覆盖范围越广,程序员同事找到他们想要的答案的几率就越大。正因为如此,我投票以重复的方式结束该问题,而不是将其全部删除。