Wednesday, 3 August 2016

Custom JSON Response class for MVC

Custom JSON Response class for MVC


using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Demo.Util
{
/// <summary>
/// A Newtonsoft.Json based JsonResult for ASP.NET MVC
/// </summary>
public class CustomJsonResult : ActionResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

/// <summary>
/// Initializes a new instance of the <see cref="JsonNetResult"/> class.
/// </summary>
public CustomJsonResult()
{
this.SerializerSettings = new JsonSerializerSettings();
}

/// <summary>
/// Gets or sets the content encoding.
/// </summary>
/// <value>The content encoding.</value>
public Encoding ContentEncoding { get; set; }

/// <summary>
/// Gets or sets the type of the content.
/// </summary>
/// <value>The type of the content.</value>
public string ContentType { get; set; }

/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data object.</value>
public object Data { get; set; }

/// <summary>
/// Gets or sets the serializer settings.
/// </summary>
/// <value>The serializer settings.</value>
public JsonSerializerSettings SerializerSettings { get; set; }

/// <summary>
/// Gets or sets the formatting.
/// </summary>
/// <value>The formatting.</value>
public Formatting Formatting { get; set; }

/// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;

response.ContentType = !String.IsNullOrWhiteSpace(this.ContentType) ? this.ContentType : "application/json";

if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}

if (this.Data != null)
{
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;

response.Write(JsonConvert.SerializeObject(Data, isoConvert));

JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = this.Formatting };

JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
serializer.Serialize(writer, this.Data);

writer.Flush();
}
}
}
}

Parent-Child class declaration and initialization

using System; namespace CSharpDemo {     public class A     {         public void print()         {             Console.Wr...