【问题标题】:How to solve this error Unable to cast object of type 'System.Int32' to type 'System.String' [closed]如何解决此错误无法将“System.Int32”类型的对象转换为“System.String”类型[关闭]
【发布时间】:2013-10-17 23:40:00
【问题描述】:

为我的网站使用表单身份验证,我收到错误

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”

谁能告诉我哪里出了问题或者我应该怎么做。

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

【问题讨论】:

  • 角色需要一个字符串。你给它一个 Int64(即长)
  • 如何给角色一个整数值
  • 我已经写了 3 个 cmets,但老实说,我的文字让我失望.... 投票关闭 ...
  • 我花了一段时间才找到有用的东西,但是拜托 read this

标签: c# string casting int form-authentication


【解决方案1】:

这是2nd constructor overload 上的FormsAuthenticationTicket Class 上的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);

【讨论】:

  • +1 有时我会绝望,我真的会。有没有觉得我们在向世界教授基本的编程技术,因为它们不会被打扰? :)
猜你喜欢
  • 1970-01-01
  • 2014-02-03
  • 2021-10-25
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多