如何减少帖子请求的时间(TTFB)?

时间:2016-05-24 13:56:40

标签: asp.net-mvc asp.net-web-api

我正在网站上工作。我同时使用MVC 5和Web api。 对于web api请求,TTFB太长(6~10 s),但mvc视图的ttfb(1~2 s)是可以接受的。 当我向同一个api发布许多请求时,只有第一个请求有问题。

这是我在Login方法中的代码

    public HttpResponseMessage Login(LoginInfo loginInfo)
    {
        string result = JsonConvert.SerializeObject(new { status = "example" });

        //check the whether user is already login
        if (HttpContext.Current.User.Identity.IsAuthenticated
            && loginInfo.UserName == (string)HttpContext.Current.Session["user"])
        {
            result = JsonConvert.SerializeObject(new { status = (string)HttpContext.Current.Session["role"] });
            return new HttpResponseMessage { Content = new StringContent(result, Encoding.UTF8, "application/json") };
        }

        Student student = studentRepo.GetById(loginInfo.UserName);
        if (student == null)
        {
            result = JsonConvert.SerializeObject(new { status = "usr" });
        }
        else
        {
            string password;
            string salt = (string)HttpContext.Current.Session["salt"];
            if (string.IsNullOrEmpty(salt))
            {
                //the login page has expired 
                result = JsonConvert.SerializeObject(new { status = "expire" });
            }
            else
            {
                password = student.Password + salt;
                password = MD5Helper.GetMd5(password);
                if (password == loginInfo.Password)
                {
                    //login success!
                    HttpContext.Current.Session.Remove("salt");
                    FormsAuthentication.SetAuthCookie(loginInfo.UserName, false);
                    HttpContext.Current.Session.Add("user", student.StuNo);
                    HttpContext.Current.Session.Add("role", student.Role);
                    result = JsonConvert.SerializeObject(new { status = student.Role });
                }
                else
                {
                    result = JsonConvert.SerializeObject(new { status = "deny" });
                }
            }
        }
        return new HttpResponseMessage { Content = new StringContent(result, Encoding.UTF8, "application/json") };
    }

1 个答案:

答案 0 :(得分:0)

现在我将我的应用程序部署到另一台服务器,TTFB变短了。并且经常删除该会话的问题也是固定的。