我使用ASP NET Core(不是旧的web api或mvc)进行简单的操作:
[HttpPost]
public async Task<SomeResponse> Something([FromBody] SomeRequest request)
{
// request is null here when the POST body is empty
}
当我发布一个空体request
时为空。我有一个全局操作过滤器,如果存在任何模型验证错误,则返回通用400响应。
public class ValidateModelBindingAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
// 400 response here.
}
}
}
如果body为空,我希望ModelState无效,以便在尝试使用null请求对象执行操作之前,验证过滤器将以400响应。我尝试在[Required]
参数中添加request
属性无效。那里有另一种解决方案吗?
答案 0 :(得分:2)
它认为Null
模型有效,因为它会在ModelState.ErrorCount
null
时检查0
这就是为什么它会将其视为有效模型,这样您就可以试试这个
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);
}
}
}
并且不要忘记在ValidateViewModel
action
属性