2016-09-23 63 views
3

使用MVC 5我返回Json。总共需要40毫秒才能返回数据。返回ActionResult后会发生什么?

然而,浏览器需要6000 millisconds才能获取数据,甚至在服务器上运行它。

我的问题是我返回值后会发生什么。我试图找出是什么原因导致缓慢。

public JsonResult Read(....) 
    { 
     var all = _userManager.GetStuff(); 
     var watch = Stopwatch.StartNew(); 
     var r= Json(all .....); 
     Trace.WriteLine("READ" + watch.ElapsedMilliseconds); 
     watch.Stop(); 

     return r; //Takes 40 milliseconds to get here 
    } 
+0

总共有多少项,东东对象是简单对象还是复杂? –

回答

1

这是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。