Created
February 27, 2012 02:55
-
-
Save ducas/1920999 to your computer and use it in GitHub Desktop.
Validating your model with Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web.Http; | |
using System.Data; | |
public class TodoApiController : ApiController | |
{ | |
private BetterMobileSpaContext db = new BetterMobileSpaContext(); | |
// GET /api/todoapi | |
public IEnumerable<TodoItem> Get() | |
{ | |
return db.TodoItems.ToList(); | |
} | |
// GET /api/todoapi/5 | |
public TodoItem Get(int id) | |
{ | |
return db.TodoItems.Find(id); | |
} | |
// POST /api/todoapi | |
[ValidateFilter] | |
public void Post(TodoItem value) | |
{ | |
if (!ModelState.IsValid) return; | |
db.TodoItems.Add(value); | |
db.SaveChanges(); | |
} | |
// PUT /api/todoapi/5 | |
[ValidateFilter] | |
public void Put(int id, TodoItem value) | |
{ | |
if (!ModelState.IsValid) return; | |
db.Entry(value).State = EntityState.Modified; | |
db.SaveChanges(); | |
} | |
// DELETE /api/todoapi/5 | |
public void Delete(int id) | |
{ | |
TodoItem todoitem = db.TodoItems.Find(id); | |
db.TodoItems.Remove(todoitem); | |
db.SaveChanges(); | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
db.Dispose(); | |
base.Dispose(disposing); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Web.Http.Filters; | |
using System.Net.Http; | |
public class ValidateFilterAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) | |
{ | |
var modelState = actionExecutedContext.ActionContext.ModelState; | |
if (!modelState.IsValid) | |
{ | |
var errors = modelState | |
.Where(s => s.Value.Errors.Count > 0) | |
.Select(s => new KeyValuePair<string, string>(s.Key, s.Value.Errors.First().ErrorMessage)) | |
.ToArray(); | |
actionExecutedContext.Result = new HttpResponseMessage<KeyValuePair<string, string>[]>(errors, HttpStatusCode.BadRequest); | |
} | |
base.OnActionExecuted(actionExecutedContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes we can handle If model is null