【问题标题】:Should I cast the value returned from User.Identity.GetUserId() to make it a GUID?我应该转换从 User.Identity.GetUserId() 返回的值以使其成为 GUID 吗?
【发布时间】:2014-07-04 12:41:20
【问题描述】:

我创建了以下类:

public class Config
{
    public Guid UserId { get; set; }
    public string AdminJSON { get; set; }
    public string UserJSON { get; set; }
}

当我查询我正在使用的数据时:

Config config = await db.Configs.FindAsync(User.Identity.GetUserId());

这是进行查找的正确方法吗?似乎 User.Identity.GetUserId() 返回一个 细绳。我是否应该将其转换为返回 GUID。

我还有另一个问题:

UserId = User.Identity.GetUserId()   

这也失败了。我尝试通过在 User.Identity.GetUserId() 之前添加 (Guid) 来进行强制转换,但是这会显示一条消息,提示错误 1 ​​无法将类型“字符串”转换为“System.Guid”

它出错了,因为它不能

【问题讨论】:

    标签: c# asp.net asp.net-identity


    【解决方案1】:

    您需要使用Guid.Parse(User.Identity.GetUserId()) 或更好的防故障方法

    Guid userId;
    bool worked=Guid.TryParse(User.Identity.GetUserId(),out userId);
    if(worked) 
    {
        //go ahead
    }
    else 
    {
        throw new Exception("Invalid userid"); 
    }
    

    【讨论】:

    • 我会省略 worked 变量,只做 if (Guid.TryParse(User.Identity.GetUserId(),out userId)) { ... }
    • 如果您的 guid 无效,您将无法继续。否则它将是 Guid.Empty 并且进一步的逻辑将中断。
    • 我的代码做的完全一样,只是避免了命名和保留返回值。
    【解决方案2】:

    转换为比第三方库提供给您的类型更严格的类型似乎是个坏主意。仅出于这个原因,我会将 UserId 保留为字符串。如果您发现它成为性能问题,您可以随时对其进行优化。

    如果您刚开始使用 asp.net Identity,我强烈建议您使用默认项目,因为它已经连接好。

    以下是我刚开始时对我有帮助的一些文章:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2016-03-01
      相关资源
      最近更新 更多