using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Data;
public class TodoApiController : ApiController
{
private AuthContext ctx = new AuthContext();
// 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)
{
db.TodoItems.Add(value);
db.SaveChanges();
}
// PUT /api/todoapi/5
[ValidateFilter]
public void Put(int id, TodoItem value)
{
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);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Web.Http.Controllers;
namespace TAMS.API.Infrastructure
{
public class ValidateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response =
actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}else if(actionContext.ActionArguments.FirstOrDefault().Value == null)
{
actionContext.ModelState.AddModelError("Model Null", "Form is empty. Please enter some value");
actionContext.Response =
actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
base.OnActionExecuting(actionContext);
}
}
}