每當我嘗試從會話(FormsAuthentication)獲取用戶標識時,我總是收到此異常(在標題中)。下面是該方法的代碼:輸入字符串格式不正確
public User GetUserFromSession()
{
int userId = int.Parse(_httpContext.User.Identity.Name); //this line throws the exception
IsNotNull(userId, "session user id");
var user = _userService.GetUserById(userId);
return user;
}
當我第一次將ID添加到會話中時,它將作爲字符串添加。我嘗試使用Convert.Int32
和Convert.Int16
,但我仍然得到相同的例外。我怎麼能阻止這種情況發生?
UPDATE:
好吧,我調試的項目和檢查的_httpContext.User.Identity.Name
的價值,它實際上是一個空字符串!我不明白爲什麼會發生這種情況...以下是我如何登錄用戶:
var authTicket = new FormsAuthenticationTicket(
1,
user.Id.ToString(), //user id
DateTime.Now,
DateTime.Now.AddDays(30), // expiry
dto.RememberMe, //true to remember
"", //roles
"/"
);
//encrypt the ticket and add it to a cookie
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
不應該這樣做嗎?還是我失去的東西在這裏...
更新2:
看看這個截圖:http://i52.tinypic.com/2cnaw00.jpg 正如你所看到的,CurrentNotification物業說,有一個例外。這可能是問題的真正根源嗎?
P.S:Helper類在構造函數中接受一個HttpContext實例,這就是我傳遞當前上下文的方式:x.For<HttpContext>().Use(HttpContext.Current);
(使用StructureMap)。
_httpContext.User.Identity.Name是否是一個整數?嘗試輸出它,看看它的樣子。我猜是的,@alex, – alex 2011-04-21 12:09:14
。因爲如果停止調試並再次運行調試器,會話將在那裏,我將正常登錄。 – Kassem 2011-04-21 12:14:23
@Kassem:還有,你看過這個字符串是怎麼看的?也許你有一封肯定不應該在那裏的信... – alex 2011-04-21 12:16:31