Model Validation in ASP.NET Web API By Mike Wasson|July 20, 2012 268 of 294 people found this helpful
2016-12-08 09:57
513 查看
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
相关文章推荐
- Model Validation in ASP.NET Web API
- Log message Request and Response in ASP.NET WebAPI
- Tracing in ASP.NET Web API
- 错误 11 类型“System.Web.Mvc.ModelClientValidationRule”同时存在于“C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages
- Replace JSON.NET with Jil JSON serializer in ASP.NET Web API
- Model Validation in Asp.net MVC
- Manual JSON serialization from DataReader in ASP.NET Web API
- A simple Test Client built on top of ASP.NET Web API Help Page
- Creating a Clean, Minimal-Footprint ASP.NET WebAPI Project with VS 2012 and ASP.NET MVC 4
- Bing Web API usage by ASP.NET(C#)
- 新建MVC3项目时出错:错误 2 类型“System.Web.Mvc.ModelClientValidationRule”同时存在于“C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.dll”和“C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3\Assembli
- HOW TO: Upload a File to a Web Server in ASP.NET by Using Visual Basic .NET
- Model Validation in Asp.net MVC
- How do I get ASP.NET Web API to return JSON instead of XML using Chrome
- Content Negotiation in ASP.NET Web API
- Routing in ASP.NET Web API
- Simple way to implement caching in ASP.NET Web API
- Replace JSON.NET with ServiceStack.Text in ASP.NET Web API
- Adding the Test API in The ASP.NET Web API Help Page
- The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the ser