用MVC6写webapi,添加model校验过滤器

来源:互联网 发布:数据库用什么软件好 编辑:程序博客网 时间:2024/06/02 02:19
需求:过滤验证实体

实体code:
[StringLength(32, MinimumLength = 1, ErrorMessage = "{0} must be a string.  Its min length is {2}, its max length is {1}.")]
[Required]
publicstringOrderID {get;set; }

过滤器代码(这里会直接抛出错误信息)
 publicclassValidateModelStateFilter:ActionFilterAttribute
    {
       publicoverridevoidOnActionExecuted(ActionExecutedContextcontext)
        {
           if(!context.ModelState.IsValid)
            {
                context.Result =newBadRequestObjectResult(context.ModelState);
            }
        }
    }
过滤器注入代码
 publicvoidConfigureServices(IServiceCollectionservices)
        {
           // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc(options =>
            {
                options.Filters.Add(newValidateModelStateFilter());
            });
                     services.AddSingleton<IOrderRepo,OrderRepo>();
                     services.AddSwaggerGen();
                     services.ConfigureSwaggerGen(options =>
                     {
                           options.SingleApiVersion(newInfo
                           {
                                  Version ="v1",
                                  Title ="Zebra VMI Api",
                                  Description ="Zebra VMI Api by @360Zebra",
                                  TermsOfService ="NA",
                                  Contact =newContact()
                                  {
                                         Name ="斑马小二",
                                         Email ="jay.shen@360zebra.com",
                                         Url ="http://www.360zebra.com"
                                  }
                           });
                     });
              }

参考链接http://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-4_4_3-filters.html

0 0
原创粉丝点击