ValidateModelAttribute

2018/07/02 209

Api自动验证模型是否正确,如果正确,执行Action中的代码,如果不正确,直接返回错误消息。
Action中将不再需要判断ModelState

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.ModelState.IsValid)
        {
            base.OnActionExecuting(context);
        }
        else
        {
            List<string> msg = new List<string>();
            foreach (var value in context.ModelState.Values)
            {
                foreach (var error in value.Errors)
                {
                    msg.Add(error.ErrorMessage);
                }
            }
            context.Result = new JsonResult(new HttpDataResult<List<string>>(true)
            {
                Code = CodeResult.BadRequest,
                Notify = NotifyResult.Warning,
                Data = msg
            });
        }
    }
}
评论