这是JsonResult
类型的内部代码。
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(MvcResources.JsonRequest_GetNotAllowed);
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;
JavaScriptSerializer scriptSerializer = new JavaScriptSerializer();
if (this.MaxJsonLength.HasValue)
scriptSerializer.MaxJsonLength = this.MaxJsonLength.Value;
if (this.RecursionLimit.HasValue)
scriptSerializer.RecursionLimit = this.RecursionLimit.Value;
response.Write(scriptSerializer.Serialize(this.Data));
}
从视内部码点,所述JavaScriptSerializer
是用于序列化传递到JsonResult
对象的类型。您可以检查这是否是您的代码采取缓慢流程的步骤。
试着让你的控制器是这样的:
public JsonResult Read(....)
{
var all = _userManager.GetStuff();
var watch = Stopwatch.StartNew();
var scriptSerializer = new JavaScriptSerializer();
var json = scriptSerializer.Serialize(all);
Trace.WriteLine("READ" + watch.ElapsedMilliseconds);
watch.Stop();
return json; //Takes 40 milliseconds to get here
}
如果问题仍然存在,你可以实现一个替代方案,你可以使用JSON.Net
库,它可以提供better results实现自己的JsonResult。对于样品,添加命名空间:
using Newtonsoft.Json;
控制器:
public JsonResult Read(....)
{
var all = _userManager.GetStuff();
var watch = Stopwatch.StartNew();
var json = JsonConvert.SerializeObject(all);
Trace.WriteLine("READ" + watch.ElapsedMilliseconds);
watch.Stop();
return Content(json, "application/json"); //Takes 40 milliseconds to get here
}
最后,你可以比较的性能。另一种可能的方法是使用另一种可以加快序列化的格式,例如xml或binary。
总共有多少项,东东对象是简单对象还是复杂? –