JsonNetResult.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using Newtonsoft.Json;
  7. namespace Bowin.Common.Mvc
  8. {
  9. public class JsonNetResult : JsonResult
  10. {
  11. public JsonNetResult()
  12. {
  13. SerializerSettings = new JsonSerializerSettings
  14. {
  15. ReferenceLoopHandling = ReferenceLoopHandling.Error,
  16. DateFormatHandling = DateFormatHandling.IsoDateFormat
  17. };
  18. }
  19. public JsonSerializerSettings SerializerSettings { get; set; }
  20. public Formatting Formatting { get; set; }
  21. public override void ExecuteResult(ControllerContext context)
  22. {
  23. if (context == null)
  24. throw new ArgumentNullException("context");
  25. HttpResponseBase response = context.HttpContext.Response;
  26. response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
  27. if (ContentEncoding != null)
  28. response.ContentEncoding = ContentEncoding;
  29. if (Data != null)
  30. {
  31. JsonTextWriter writer = new JsonTextWriter(response.Output)
  32. {
  33. Formatting = Formatting
  34. };
  35. JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
  36. serializer.Serialize(writer, Data); writer.Flush();
  37. }
  38. //if (context == null)
  39. // throw new ArgumentNullException("context");
  40. //if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
  41. // throw new InvalidOperationException("JSON GET is not allowed");
  42. //HttpResponseBase response = context.HttpContext.Response;
  43. //response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
  44. //if (this.ContentEncoding != null)
  45. // response.ContentEncoding = this.ContentEncoding;
  46. //if (this.Data == null)
  47. // return;
  48. //var scriptSerializer = JsonSerializer.Create(this.Settings);
  49. //using (var sw = new StringWriter())
  50. //{
  51. // scriptSerializer.Serialize(sw, this.Data);
  52. // response.Write(sw.ToString().Trim('[', ']'));
  53. //}
  54. }
  55. }
  56. }