I’ve recently moved a project over Web Api over to ASP.NET Web Api. In doing that I needed to re-implement my validation code. Thanks to the Api being a part of the MVC framework, things are much simpler now.
Previously I was Explained About Difference between WCF and Web API and WCF REST and Web Service , Repeater Vs. DataList vs. ListView Vs. GridView , IEnumerable VS IQueryable
All I need do now is decorate my models appropriately, for example …
I will get a HTTP 400 response with a nice array of key/value pairs in the response body whenever a client sends me bad data.
Previously I was Explained About Difference between WCF and Web API and WCF REST and Web Service , Repeater Vs. DataList vs. ListView Vs. GridView , IEnumerable VS IQueryable
public class ValidationActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext context) { var modelState = context.ModelState; if (!modelState.IsValid) { dynamic errors = new JsonObject(); foreach (var key in modelState.Keys) { var state = modelState[key]; if (state.Errors.Any()) { errors[key] = state.Errors.First().ErrorMessage; } } context.Response = new HttpResponseMessage<JsonValue>( errors, HttpStatusCode.BadRequest); } } } |
public class TellAFriend { [StringLength(100)] public string ToName { get ; set ; } [StringLength(100)] [Required] [RegularExpression(Regexes.EmailPattern, ErrorMessage = "Invalid email address" )] public string ToEmailAddress { get ; set ; } }
|
{ "ToEmailAddress" : "Invalid email address" }
Source From :
http://www.dotnetcurry.com/ShowArticle.aspx?ID=927
http://msdn.microsoft.com/en-us/magazine/dn201742.aspx
|
Comments
Post a Comment