第一种:直接在执行action之前验证模型 实现 IActionFilter
public class ModelStateFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { ModelStateDictionary modelState = context.ModelState; if (!modelState.IsValid) { context.Result = new BadRequestObjectResult(modelState); } } public void OnActionExecuted(ActionExecutedContext context) { } }
第二种 属性的实现
/// <summary> /// 简化模型验证 modelState.IsValid不用每一个写 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)] public class ModelValidationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { ModelStateDictionary modelState = context.ModelState; if (!modelState.IsValid) { context.Result = new BadRequestObjectResult(modelState); } } }