59 lines
1.6 KiB
C#
59 lines
1.6 KiB
C#
namespace ChatRoomServer.Www.Models
|
|
{
|
|
using System;
|
|
using System.Web.Mvc;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
/// <summary>
|
|
/// 使用Json.Net进行序列化的结果
|
|
/// </summary>
|
|
public class Json2Result : JsonResult
|
|
{
|
|
static JsonSerializerSettings _camelJsonSetting = new JsonSerializerSettings
|
|
{
|
|
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
|
};
|
|
|
|
/// <summary>
|
|
/// 获得或设置经行回调的js函数名
|
|
/// </summary>
|
|
public string CallbackJsFunction { get; set; }
|
|
|
|
/// <summary>
|
|
/// 获得是否使用缩进
|
|
/// </summary>
|
|
public bool Indent { get; set; }
|
|
|
|
/// <summary>
|
|
/// 获得或设置是否使用Camel命名方式
|
|
/// </summary>
|
|
public bool UseCamelName { get; set; }
|
|
|
|
public override void ExecuteResult(ControllerContext context)
|
|
{
|
|
var request = context.HttpContext.Request;
|
|
CallbackJsFunction = CallbackJsFunction.DefaultForEmpty(request.QueryString["callback"] ?? "");
|
|
|
|
|
|
var response = context.HttpContext.Response;
|
|
response.ContentType = ContentType.DefaultForEmpty(CallbackJsFunction.IsNullOrEmpty() ? "application/json" : "text/javascript");
|
|
if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
|
|
|
|
if (Data != null)
|
|
{
|
|
if (!CallbackJsFunction.IsNullOrEmpty())
|
|
{
|
|
response.Write(CallbackJsFunction);
|
|
response.Write("(");
|
|
}
|
|
response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data, Indent ? Formatting.Indented : Formatting.None, UseCamelName ? _camelJsonSetting : null));
|
|
if (!CallbackJsFunction.IsNullOrEmpty())
|
|
{
|
|
response.Write(")");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|