by thorhalvor

Asp.NET MVC 3 and JSON

Creating a ASP.NET MVC 3 REST API returning JSON data is actually really simple.

If you have a MVC 3 Visual Studio project template and you add a Controller the default HomeController will be added:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

 

If you want this Index to return Json data the only thing needed is return JsonResult instead of a View.

        //return View();
        return new JsonResult();

 

To give an example I have created a ProductsController returning 3 products with the properties ProductId, Name and Price.

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult All()
{
    var data = GetProducts();
    return new JsonpResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Notice that you have to set JsonRequestBehavior.AllowGet. If forgotten you will get the self-explanatory errormessage:

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. 
To allow GET requests, set JsonRequestBehavior to AllowGet.

 

When sending the request GET http://localhost/Website/Products/All, the method will return my three products:

(using Chrome with the extension JSONView)

json

As simple as that Smile