gpt4 book ai didi

c# - ActionResult 返回后会发生什么?

转载 作者:行者123 更新时间:2023-11-30 17:36:23 24 4
gpt4 key购买 nike

我使用 MVC 5 返回 Json。到达数据返回点的总时间为 40 毫秒。

然而,即使在服务器上运行它,浏览器也需要 6000 毫秒 才能获取数据。

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

    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
}

最佳答案

这是 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 的对象的类型。您可以检查这是否是您的代码处理缓慢的步骤。

试着让你的 Controller 像这样:

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 实现您自己的 JsonResult图书馆,可以提供better results .对于 Sample,添加命名空间:

using Newtonsoft.Json; 

Controller :

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 或二进制。

关于c# - ActionResult 返回后会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com