• Fluent Validation with Web Api 2


    1. nuget添加FluentValidation.WebApi引用.

    2. 模型定义:

        [Validator(typeof(CustomerValidator))]
        public class UserModel
        {
            public string UserName { get; set; }
            public string Password { get; set; }
        }

    3. Validator定义:

        public class CustomerValidator : AbstractValidator<UserModel>
        {
            public CustomerValidator()
            {
                RuleFor(customer => customer.UserName).NotEmpty();
                RuleFor(customer => customer.Password).NotEmpty().WithMessage("Please specify a first name");
            }
        }

    4. Controller定义:

        public class DefaultController : ApiController
        {
            // POST: api/Default
            public bool Post([FromBody]UserModel user)
            {
                //var validator = new CustomerValidator();
                //var results = validator.Validate(user);
    
                return user.UserName == "admin";
            }
        }

    5. Validation Action Filter定义:

        public class ValidateModelStateFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (!actionContext.ModelState.IsValid)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
                }
            }
        }

    6. 最后在WebApp启动时注册注册ValidationFilter:

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Filters.Add(new ValidateModelStateFilter());
                FluentValidationModelValidatorProvider.Configure(config);
            }
        }

    7. 测试:

  • 相关阅读:
    Microsoft Office MIME Types
    启动mongodb
    学习Hbase API的一个视频
    报错:Hive Runtime Error while processing row
    821. Shortest Distance to a Character
    1171. Remove Zero Sum Consecutive Nodes from Linked List
    190. Reverse Bits
    Rust--如何实现内存安全的?
    Rust -- as_ref与borrow的区别
    653. Two Sum IV
  • 原文地址:https://www.cnblogs.com/lenmom/p/8601736.html
Copyright © 2020-2023  润新知