ASP.NET MVC 2 Cookbook
上QQ阅读APP看书,第一时间看更新

Exposing JSON using a JsonResult with Json.NET

In this recipe, we will take a look at the new JsonResult that comes with the MVC 2 framework.

Getting ready

We will use Json.NET (in the dependencies folder) to convert an object to JSON for us. And we will be using the Product class from the Using magic strings and the ViewData dictionary recipe ofChapter 1. We will also be using NBuilder (also in the dependencies folder) to hydrate a Product instance.

How to do it...

  1. Start a new ASP.NET MVC application.
  2. Add a reference to Json.NET.
  3. Add a reference to NBuilder.
  4. Create a new action named GetJson inside your HomeController. Instead of returning an ActionResult, we will specify that it will return a JsonResult.

    HomeController.cs:

    public JsonResult GetJson()
    {
    }
    
  5. Add the Product class to your Models folder (or create a new Product class).
  6. Make sure that the Product class is set to [Serializable].

    Product.cs:

    using System;
    namespace ExposingJSONFromJsonResult.Models
    {
    [Serializable]
    public class Product
    {
    public string Sku { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public double Cost { get; set; }
    }
    }
    
  7. Now we can specify our result by asking NBuilder to spit out an instance of Product. We can convert our Product object into JSON using a built-in method Json.

    Note

    When producing JSON in a Get method (as we are), you will also need to specify the JsonRequestBehavior to AllowGet. This is considered an XSS vulnerability though, so this is purely to render it in the browser as proof that it worked. Generally, you would want to use a Post method with something like jQuery to get your JSON payload off the server.

    HomeController.cs:

    public JsonResult GetJson()
    {
    return Json(Builder<Product>.CreateNew().Build(), JsonRequestBehavior.AllowGet);
    }
    

How it works...

Short of using NBuilder, we have utilized the power of the new MVC 2 framework to generate a JSON result for us. It even took care of the serialization for us.

There's more...

Be aware that exposing JSON via GET requests on your site potentially opens you up to cross-site scripting attacks. However, not allowing GET requests doesn't necessarily make you safe either—although it helps. Take a look at this discussion on Stack Overflow concerning this topic: http://stackoverflow.com/questions/1625671/what-is-the-problem-with-a-get-json-request.

See also

You might also be interested to know that there are the following other types of ActionResult classes:

  • ViewResult
  • EmptyResult
  • RedirectResult
  • JavaScriptResult
  • ContentResult
  • FileContentResult
  • FilePathResult
  • FileStreamResult