每当我尝试从会话(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