JsonController.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Web;
  3. using System.Web.Mvc;
  4. namespace Benchmarks.AspNet.Controllers
  5. {
  6. public class JsonController : Controller
  7. {
  8. public ActionResult Default()
  9. {
  10. return new JsonResult { Data = new { message = "Hello World" } };
  11. }
  12. public ActionResult JsonNet()
  13. {
  14. return new JsonNetResult { Data = new { message = "Hello World" } };
  15. }
  16. public ActionResult ServiceStack()
  17. {
  18. return new ServiceStackResult { Data = new { message = "Hello World" } };
  19. }
  20. }
  21. public class JsonResult : ActionResult
  22. {
  23. public object Data
  24. {
  25. get;
  26. set;
  27. }
  28. public override void ExecuteResult(ControllerContext context)
  29. {
  30. if (context == null)
  31. throw new ArgumentNullException("context");
  32. HttpResponseBase response = context.HttpContext.Response;
  33. response.ContentType = "application/json";
  34. if (Data != null)
  35. {
  36. response.Write(Serialize());
  37. }
  38. }
  39. protected virtual string Serialize()
  40. {
  41. return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Data);
  42. }
  43. }
  44. public class JsonNetResult : JsonResult
  45. {
  46. protected override string Serialize()
  47. {
  48. return Newtonsoft.Json.JsonConvert.SerializeObject(Data);
  49. }
  50. }
  51. public class ServiceStackResult : JsonResult
  52. {
  53. protected override string Serialize()
  54. {
  55. return ServiceStack.Text.JsonSerializer.SerializeToString(Data);
  56. }
  57. }
  58. }