以前在 WebAPI 项目中,我使用ValidateModelAttribute避免if (!ModelState.IsValid)在我的每个控制器中重复语句。
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
当我尝试在 MVC 控制器 (ASP.NET Core 2.1) 中的操作上使用相同的属性时,我收到 400 状态代码,页面仅显示错误的 JSON 表示,例如{"Description":["Description is required"]}.
是否有类似的属性可以在我的 MVC 控制器中使用,以与使用相同的方式将 ModelState 错误转发到我的视图
if (!ModelState.IsValid)
{
return View(command);
}
慕沐林林
相关分类