asp.net core 简化模型验证 modelState.IsValid不用每一个写

第一种:直接在执行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);
            }
        }
    }

 

posted @ 2018-09-14 01:03  SpeakHero  阅读(1991)  评论(0编辑  收藏  举报