Friday, 16 March 2012

MVC3 Restful JSON example

This is a Restful API for the MVC3 example from the previous post.

Get: GET /Api/Product/{id}
Create: POST /Api/Product
Update: PUT /Api/Product
Delete: DELETE /Api/Product/{id}

Create ApiController

public class ApiController : Controller
{
    DatabaseEntities entities = new DatabaseEntities();
    [HttpGet]
    [ActionName("Product")]
    public JsonResult Get(Guid id)
    {
        return Json(entities.Products.FirstOrDefault(x => x.Id == id), JsonRequestBehavior.AllowGet);
    }
    [HttpPost]
    [ActionName("Product")]
    public JsonResult Create(Product product)
    {        
        product.Id = Guid.NewGuid();
        entities.Products.AddObject(product);
        entities.SaveChanges();
        return Json(product);
    }
    [HttpPut]
    [ActionName("Product")]
    public JsonResult Update(Product product)
    {
        var current = entities.Products.FirstOrDefault(x => x.Id == product.Id);
        current.Name = product.Name;
        
        entities.SaveChanges();
        return Json(current);
    }
    [HttpDelete]
    [ActionName("Product")]
    public JsonResult Delete(Guid id)
    {
        entities.Products.DeleteObject(entities.Products.FirstOrDefault(x=>x.Id==id));
        entities.SaveChanges();
        return Json(true);
    }
}

And test it with Fiddler

-------
Create
-------
Url:
POST http://localhost:52292/Api/Product
Request Headers:
User-Agent: Fiddler
Host: localhost:52292
Content-Type: application/json; charset=utf-8
Content-Length: 21
Request Body:
{"Name":"Strawberry"}
-------
Get
-------
Url:
GET http://localhost:52292/Api/Product/5d2effcb-042d-4836-9125-c256ff955a73
Request Headers:
User-Agent: Fiddler
Host: localhost:52292
-------
Update
-------
Url:
PUT http://localhost:52292/Api/Product
Request Headers:
User-Agent: Fiddler
Host: localhost:52292
Content-Type: application/json; charset=utf-8
Content-Length: 62
Request Body:
{"Id":"848e791c-4161-447d-b6cb-7d9e1a2648a5",Name:"Raspberry"}
-------
Insert
-------
Url:
DELETE http://localhost:52292/Api/Product/5d2effcb-042d-4836-9125-c256ff955a73
Request Headers:
User-Agent: Fiddler
Host: localhost:52292

No comments:

Post a Comment