1. 程式人生 > >Net Core 全域性模型驗證

Net Core 全域性模型驗證

 1 public class ActionFilter : IActionFilter
 2     {
 3 
 4         /// <summary>
 5         /// action 執行之前
 6         /// </summary>
 7         /// <param name="context"></param>
 8         public void OnActionExecuting(ActionExecutingContext context)
 9         {
10             #region 全域性 Model 驗證過濾  
11
if (context.ModelState.IsValid) return; 12 var result = new ResponseData<object>(); 13 foreach (var item in context.ModelState.Values) 14 { 15 foreach (var error in item.Errors) 16 { 17 result.Status = MessageInfo.StatusFailed;
18 result.Message = error.ErrorMessage; 19 if (string.IsNullOrEmpty(result.Message)) 20 { 21 result.Message = "Verification is not necessary."; 22 } 23 context.Result = new JsonResult(result);
24 break; 25 } 26 } 27 #endregion 28 } 29 }