2010-09-28 38 views
3

我正在寫一個asp.net MVC 2.0應用程序,我需要在用戶登錄後將用戶名傳遞給其他函數。我想,通過簡單修改了的AccountController標準的登錄方法,這裏是我的代碼:登錄後,爲什麼user.Identity.Name爲空? Asp.net mvc 2.0

[HttpPost] 
    public ActionResult LogOn(LogOnModel model, string returnUrl) 
    { 
     if (ModelState.IsValid) 
     { 
      if (MembershipService.ValidateUser(model.UserName, model.Password)) 
      { 

       FormsService.SignIn(model.UserName, model.RememberMe); 
       using (ShopController newCtrl = new ShopController()) 
       { 
        if (Session["TempCart"] != null) 
        { 

         newCtrl.CreateShoppingCartFromSession((Cart)Session["TempCart"], User.Identity.Name); 
        } 
       } 
       if (!String.IsNullOrEmpty(returnUrl)) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
      } 
      else 
      { 
       ModelState.AddModelError("", "The user name or password provided is incorrect."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

的問題是,即使用戶成功登錄,則「User.Identity.Name」是空白,我不知道爲什麼...

任何幫助將不勝感激。

回答

6

表單身份驗證方法設置一個身份驗證Cookie,該cookie在下一個請求中首次被讀取和處理,因此User.Identity只能從下一個請求中變爲可用。

在這種方法中,您必須首先執行重定向或使用您的model.UserName