zoukankan      html  css  js  c++  java
  • [.NetCore] 统一模型验证拦截器

    参考:

    1. 关闭默认模型验证过滤器
      [ApiController] 默认自带有400模型验证,且优先级比较高,如果需要自定义模型验证,则需要先关闭默认的模型验证
      在StartUp.cs 中的MVC服务配置修改

      #region MVC
      services.AddMvc(o =>
      {
      }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
      .ConfigureApiBehaviorOptions(o =>
      {
          o.SuppressModelStateInvalidFilter = true;
      });
       #endregion
      
    2. 首先定义统一输出的格式为

      {
          code:
          errors:[
              filed:
              message:
          ]
      }
      
    3. 添加自定义模型验证DTO

       public class ErrorResultDTO
          {
              /// <summary>
              /// 参数领域
              /// </summary>
              public string Field { get; set; }
      
              /// <summary>
              /// 错误信息
              /// </summary>
              public string Message { get; set; }   
          }
      
    4. 添加过滤器
      过滤器继承自:ActionFilterAttribute, IActionFilter

      public class ModelActionFiter :ActionFilterAttribute, IActionFilter
          {
              public ModelActionFiter()
              {
              }
              public override void OnActionExecuted(ActionExecutedContext context)
              {
                  
              }
      
             public override void OnActionExecuting(ActionExecutingContext context)
              {
                  if (!context.ModelState.IsValid)
                  {     
                      List<ErrorResultDTO> errorResults = new List<ErrorResultDTO>();
                      foreach (var item in context.ModelState)
                      {
                          var result = new ErrorResultDTO
                          {
                              Field = item.Key,
                              Msg = "",
                          };
                          foreach (var error in item.Value.Errors)
                          {
                              if (!string.IsNullOrEmpty(result.Msg))
                              {
                                  result.Msg += '|';
                              }
                              result.Msg += error.ErrorMessage;
                          }
                          errorResults.Add(result);
                      }
                      context.Result = new BadRequestObjectResult(new
                      {
                          Code = StatusCodes.Status400BadRequest,
                         Errors = errorResults
                      });  
                  }
              }
          }
      
    5. 将写的过滤器注册到全局

        services.AddMvc(o =>
              {
                  o.Filters.Add(new ModelActionFiter());
         })
      
    6. 结果测试

    7. 扩展

      • 利用拦截器来测试action 的运行时间,记录日志,并设置时间限制,超过某个时间段自动发送邮件通知维护人员
  • 相关阅读:
    动画02
    动画01
    css过渡
    06强制类型转换
    05强制类型转换
    jetson 安装opencv4.4.0
    cpp中的内置异常
    cpp中std::string和std::wstring 相互转换
    qt creator杂记
    win10 git bash 使用vim 显示 git log
  • 原文地址:https://www.cnblogs.com/minskiter/p/11601873.html
Copyright © 2011-2022 走看看