如何解决此错误无法将“System.Int32”类型的对象强制转换为“System.String”类型

时间:2013-10-10 09:26:25

标签: c# string casting int form-authentication

使用我的网站的表单身份验证,我在

中收到错误
if (reader1.Read())
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
               1,
               tbDomainID.Text,
               DateTime.Now,
               DateTime.Now.AddMinutes(30),
               true,
               role = reader1.GetInt64(0),// this line
               FormsAuthentication.FormsCookiePath);
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(
            FormsAuthentication.FormsCookieName,
            hash);
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);

当我将其从GetString(0)转换为GetInt64(0)时,会显示另一个错误

  

无法将类型'long'隐式转换为'string'

任何人都可以告诉我哪里出错或者我应该做什么。

我从我的数据库中获取整数值。

1 个答案:

答案 0 :(得分:1)

这是FormsAuthenticationTicket Class2nd constructor overload上的UserData参数。

正如您所看到的那样,我们需要一个字符串,reader1.GetInt64(0)将返回long

解决这个问题的方法就是像这样调用.ToString()

role = reader1.GetInt64(0).ToString(),// this line

虽然,我不确定我是否愿意在您将变量传递给构造函数的同时设置变量。我个人也是这样做的:

if (reader1.Read())
{
    role = reader1.GetInt64(0).ToString();

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1,
        tbDomainID.Text,
        DateTime.Now,
        DateTime.Now.AddMinutes(30),
        true,
        role,
        FormsAuthentication.FormsCookiePath);

    string hash = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName,
        hash);

    if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
    Response.Cookies.Add(cookie);