2016-02-02 95 views
2

我有一個基於ASP.NET MVC框架的網站。雖然我使用異步方法登錄用戶,但我發現永久需要用戶登錄到網站。我使用了Visual Studio的診斷工具,發現這行代碼在執行代碼的過程中佔用了大部分時間。UserManager.FindByNameAsync ASP.NET MVC中的緩慢

var user = await UserManager.FindByNameAsync(model.Email); 

全碼:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(model); 
     } 

     var user = await UserManager.FindByNameAsync(model.Email); 
     if (user != null) 
     { 
      var getPasswordResult = UserManager.CheckPassword(user, model.Password); 

      if (getPasswordResult) 
      { 
       AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 

       var identity = await UserManager.CreateIdentityAsync(
          user, DefaultAuthenticationTypes.ApplicationCookie); 

       AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity); 

       if (model.RememberMe == true) 
       { 
        HttpCookie cookie = new HttpCookie("UsersLogin"); 
        cookie.Values.Add("UserName", model.Email); 
        cookie.Expires = DateTime.Now.AddDays(15); 
        Response.Cookies.Add(cookie); 
       } 



       return RedirectToAction("NavigateAuthUser", "Home", new { ReturnUrl = returnUrl }); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Invalid login attempt."); 
       return View(model); 
      } 
     } 

     return new EmptyResult(); 
    } 

以提高性能的任何建議? 感謝 Sanjeev

+1

也看到了這個問題,請點擊登錄按鈕需要1秒。 –

回答

2

對於解決方法我用:

_db.Users.First(x => x.UserName == User.Identity.Name); 

但我敢肯定這是不是最好的辦法