using System;
using System.Web.Mvc;
using Neo.Afx.ComponentModel;
namespace Neo.Afx.Mvc
{
///
/// A JSON result extension.
///
public class JsonResultEx : JsonResult
{
readonly private JsonSerializerOptions _options;
///
/// Initializes a new instance of the class.
///
public JsonResultEx() :
this(JsonSerializerOptions.All)
{
}
///
/// Initializes a new instance of the class.
///
/// The serialization options.
public JsonResultEx(JsonSerializerOptions options)
{
_options = options;
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
///
/// Enables processing of the result of an action method by a custom type that inherits from the class.
///
/// The context within which the result is executed.
/// The parameter is null.
public override void ExecuteResult(ControllerContext context)
{
if(context == null)
{
throw new ArgumentNullException("context");
}
if((JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("MvcResources.JsonRequest_GetNotAllowed");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if(ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if(Data != null)
{
response.Write(Data.ToJson(_options));
}
}
}
}