• Fluent Validation with Web Api 2


    using FluentValidation;
    using FluentValidation.Attributes;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    namespace webapiTest.Controllers
    {
    public class DefaultController : ApiController
    {
    // GET: api/Default
    public IEnumerable<string> Get()
    {
    return new string[] { "value1", "value2" };
    }

    // GET: api/Default/5
    public string Get(int id)
    {
    return "value";
    }

    // POST: api/Default
    public bool Post([FromBody]UserModel user)
    {
    //var validator = new CustomerValidator();
    //var results = validator.Validate(user);

    return user.UserName=="admin";
    }

    // PUT: api/Default/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/Default/5
    public void Delete(int id)
    {
    }
    }

    [Validator(typeof(CustomerValidator))]
    public class UserModel
    {
    public string UserName { get; set; }
    public string Password { get; set; }
    }
    public class CustomerValidator : AbstractValidator<UserModel>
    {
    public CustomerValidator()
    {
    RuleFor(customer => customer.UserName).NotEmpty();
    RuleFor(customer => customer.Password).NotEmpty().WithMessage("Please specify a first name");
    }
    }


    }

    注册:

    using FluentValidation.WebApi;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;

    namespace webapiTest
    {
    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    // Web API 配置和服务

    // Web API 路由
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

    //Fluent Validation
    config.Filters.Add(new ValidateModelStateFilter());
    FluentValidationModelValidatorProvider.Configure(config);
    }
    }
    }

    过滤器:

    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;

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

    结果:

    {
    "Message": "请求无效。",
    "ModelState": {
    "user.Password": [
    "Please specify a first name"
    ]
    }
    }

     参考;http://nodogmablog.bryanhogan.net/2016/12/fluent-validation-with-web-api-2/

    https://stackoverflow.com/questions/12975291/how-to-hook-fluentvalidator-to-a-web-api/21350606

    demo:http://nodogmablog.bryanhogan.net/wp-content/uploads/2016/12/FluentValidationExample.zip

  • 相关阅读:
    mybatis 中的稍微复杂些的sql语句
    Why doesn't Genymotion run on Windows 10?
    java.lang.NoSuchMethodError: 属于jar包冲突
    sqlserver修改某列为行号
    手机App开发
    java连接SQLserver
    svn忽略target
    JaxWsDynamicClientFactory弃用了,改成org.codehaus.xfire.client;
    FileDataSource java的文件操作
    解决Navicat无法连接Oracle的问题
  • 原文地址:https://www.cnblogs.com/kingreatwill/p/7068915.html
Copyright © 2020-2023  润新知