zoukankan      html  css  js  c++  java
  • Web Api 模型验证

    1.模型建立,在模型上类上添加System.ComponentModel.DataAnnotations验证属性

    public class Product
    {
            public int Id { get; set; }
            [Required]
            public string Name { get; set; }
            public decimal Price { get; set; }
            [Range(0, 999)]
            public double Weight { get; set; }
    }
    

    2.在ApiController类中使用验证结果

     public HttpResponseMessage Post(Product product)
            {
                if (ModelState.IsValid)
                {
                    // Do something with the product (not shown).
    
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
            }
    

    3.客户端调用并处理验证出错信息

     static async Task RunAsync()
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:57332/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                  
                    // HTTP POST
                    var gizmo = new Product() { Name = "Gizmo", Price = 100, Weight = -200 };
                    HttpResponseMessage response = await client.PostAsJsonAsync("api/Product", gizmo);
    
                    if (response.IsSuccessStatusCode)
                    {
                        // Get the URI of the created resource.
                        Uri gizmoUrl = response.Headers.Location;
                        Console.WriteLine("Post OK!");
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {                   
                        var x = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(x); //输出出错信息
                    
                    }
                }
            }
    

    4.利用Filter Attribute来统一处理验证出错信息

    建立Filter类

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

    在WebApiConfig.cs中添加如下代码

    public static void Register(HttpConfiguration config)
    {
                
          config.Filters.Add(new ValidateModelAttribute()); //将这行代码添加进去
     }
    
    
    

    这样action中就可以直接写验证通过后的业务逻辑了,在每个action不需要单独使用 if (ModelState.IsValid)方法来判断了,代码变得简洁明了

     [ValidateModel]
        public HttpResponseMessage Post(Product product)
        {
             // Do something with the product (not shown).
    
                    return new HttpResponseMessage(HttpStatusCode.OK);
        }
    

    5.验证效果

    响应信息

    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
    {
      Pragma: no-cache
      X-SourceFiles: =?UTF-8?B?ZDpcbXkgZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xNb2RlbFZhbGlkYXRpb25EZW1vXE1vZGVsVmFsaWRhdGlvbkRlbW9cYXBpXFByb2R1Y3Q=?=
      Cache-Control: no-cache
      Date: Thu, 07 Apr 2016 14:12:21 GMT
      Server: Microsoft-IIS/8.0
      X-AspNet-Version: 4.0.30319
      X-Powered-By: ASP.NET
      Content-Length: 109
      Content-Type: application/json; charset=utf-8
      Expires: -1
    }}
    

    返回XML类型出错信息

    返回json格式数据

    {"Message":"请求无效。","ModelState":{"product.Weight":["字段 Weight 必须在 0 和 999 之间。"]}}

  • 相关阅读:
    小程序事件参数传递
    java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig
    SSM单元测试时出现:Failed to load ApplicationContext的一种可能解决办法
    Cannot resolve classpath entry: /Program Files/IBM/SQLLIB/java/db2java.zip
    python 批量重命名文件
    abp + vue 模板新建页面
    Git 新建版本库命令
    vi/vim 行删除操作
    abp angular 前端权限控制
    杨辉三角-python
  • 原文地址:https://www.cnblogs.com/ywolf123/p/ValidateModelInWebApi.html
Copyright © 2011-2022 走看看