有两个地方可以调音:
- 可自行查询
- Controller.Json的序列化方法
对于 IQuerable 查询,您可以尝试 sql profiler 或尝试在返回之前调用 ToList() 以查看需要多长时间并可能对其进行优化
(如果不了解您的查询,我无法帮助您)。
但对于第二部分,您可以尝试使用 Json.Net 之类的库对结果进行序列化
从source 代码中可以看出,当你调用Json() 时,Mvc 使用JavaScriptSerializer 进行json 序列化。 (你也可以通过查看源代码来了解实际发生的情况)
从 json.net 网站的对比图中,JavaScriptSerializer 的表现相当糟糕。
所以你可以尝试使用 Json.Net 实现你自己的 JsonActionResult,下面是一些示例代码:
来源:Using JSON.NET to return ActionResult
在您的控制器(或基本控制器)中
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
以及 JsonNetResult 的定义:
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}