zoukankan      html  css  js  c++  java
  • ASP.NET Web API 数据验证

    第一种方式单独为每一个Action做验证

     // POST api/values
            public HttpResponseMessage Post([FromBody]UserInfo userInfo)
            {
             
                if (string.IsNullOrWhiteSpace(userInfo.Gender))
                {
                    ModelState.AddModelError("Gender", "性别不能为空");
                }
    
                if (ModelState.IsValid)
                {
                    // Do something with the product (not shown).
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
            }
    public class UserInfo
        {
            public int Id { get; set; }
            [Required]
            [StringLength(20, ErrorMessage = "名字太长了或者太短了", MinimumLength = 4)]
            public string Name { get; set; }
    
            [RegularExpression(@"([2-5]d)", ErrorMessage = "年龄在20-50之间")]
            public int Age { get; set; }
    
            public string Gender { get; set; }
        }

    第二种做全局验证:

     public class ValidationAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (!actionContext.ModelState.IsValid)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest,
                        actionContext.ModelState);
                }
            }
        }
    
    WebApiConfig.cs
    
       config.Filters.Add(new ValidationAttribute());
  • 相关阅读:
    游戏方案
    团队介绍
    【面向对象程序设计】作业四
    FIFO与LRU实现(Java)
    spring事务介绍
    微信抢红包算法
    Hibernate Dao映射配置通用接口类反射获取加载calass实例
    股票两次买卖最大收益(java)
    Eclipse安装JD-Eclipse反编译插件看源码
    Java GC调优
  • 原文地址:https://www.cnblogs.com/yxlblogs/p/4224630.html
Copyright © 2011-2022 走看看