每当我尝试从会话中获取用户ID(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
,但我仍然遇到了同样的异常。我怎么能阻止这种情况发生?
更新
好的,我调试了项目并检查了_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)。
答案 0 :(得分:1)
尝试使用FormsAuthentication.SetAuthCookie()(http://msdn.microsoft.com/en-us/library/twk5762b.aspx)来查看是否有效,而不是自己创建cookie。
你提到这个现在可以在上面的评论中使用,但是我担心为什么没有在代码示例中看到更多上下文。它可能与您传递给FormsAuthenticationTicket构造函数的参数有关(请查看http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx处的示例 - 在您的情况下,表单cookie路径参数可能是错误的吗?)。尝试使用FormsAuthentication.FormsCookiePath作为最后一个参数,而不是“/”只是为了消除这种可能性。
答案 1 :(得分:0)
如果您尝试解析为整数的字符串不是有效整数,则会出现此异常。例如,如果当前连接的用户的用户名是“john”:
int userId = int.Parse("john");
你会得到这个例外。
答案 2 :(得分:0)
可能是因为httpContext.User.Identity.Name是用户名,而不是用户ID。
答案 3 :(得分:0)
_httpContext.User.Identity.Name可能无法解析为整数。您应该调试或打印Identity.Name属性以确保它可以作为整数计算,或使用int.TryParse()来计算字符串以避免异常(取决于您的要求)。
答案 4 :(得分:0)
问题是您尝试解析的字符串不是数字。请参阅Parse() method上的文档。
FormatException:s不包含 仅可选的负号 接着是一系列数字 范围从0到9。
您可能想要使用TryParse()。这样,解析失败将返回false而不是创建异常。
同样名称是一个整数还是你打算使用其他包含整数的字段?
答案 5 :(得分:0)
传递给FormatException
的{{1}}确实包含有效数字时int.Parse
引发string
。