• Model Validation in ASP.NET Web API By Mike Wasson|July 20, 2012 268 of 294 people found this helpful


    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    using System.Web.Http.ModelBinding;
    
    namespace MyApi.Filters
    {
        public class ValidateModelAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (actionContext.ModelState.IsValid == false)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest, actionContext.ModelState);
                }
            }
        }
    }
    

      Corresponding result pasted below:

    HTTP/1.1 400 Bad Request
    Content-Type: application/json; charset=utf-8
    Date: Tue, 16 Jul 2013 21:02:29 GMT
    Content-Length: 331
    
    {
      "Message": "The request is invalid.",
      "ModelState": {
        "product": [
          "Required property 'Name' not found in JSON. Path '', line 1, position 17."
        ],
        "product.Name": [
          "The Name field is required."
        ],
        "product.Weight": [
          "The field Weight must be between 0 and 999."
        ]
      }
    }
    

      Pasted below exception the link, global exception handling in webapi

  • 相关阅读:
    prufer 序列 学习笔记
    题解 [SDOI2009]E&D/染色游戏/Moving Pebbles
    题解 Christmas Game
    题解 [HNOI/AHOI2018]毒瘤
    题解 UVA1500 Alice and Bob
    Mac端影片压制流程
    react:Text nodes cannot appear as a child
    阿里云docker镜像地址
    Vscode 智能插件
    vue-vant实现IndexBar索引栏
  • 原文地址:https://www.cnblogs.com/hualiu0/p/6143778.html
Copyright © 2020-2023  润新知