【问题标题】:How can the Identity.GetUserId() be made to return a Guid instead of a string?如何使 Identity.GetUserId() 返回 Guid 而不是字符串?
【发布时间】:2015-04-05 17:37:27
【问题描述】:

我正在使用 ASP.Net Identity 2,但很快希望在它变得更稳定时更改为 Identity 3(有人知道那可能是什么时候吗?)。这是我的代码示例:

content.ModifiedBy = User.Identity.GetUserId();

Content 表将 ModifedBy 存储为 UNIQUEIDENTIFIER,Content 对象将 Guid 数据类型分配给 ModifiedBy

当我查看 GetUserId() 的签名时,它会返回一个字符串。

那么我怎样才能将用户的 UserId 放入作为 Guid 的 ModifiedBy 中?

【问题讨论】:

  • 这是因为UserId不能只是一个guid,所以如果你确定你只使用guid,你需要自己转换。 Identity V3 适用于 ASP.NET 5,因此预计 v3 将与新的 ASP.NET 大约同时发布。

标签: asp.net asp.net-identity asp.net-identity-2 asp.net-identity-3


【解决方案1】:

guid 可以将字符串作为构造函数

content.ModifiedBy = new Guid(User.Identity.GetUserId());

【讨论】:

  • 我会采用这种方法。有一个通用版本GetUserId<T>,但在它下面使用Convert.ChangeType,它需要值参数来实现IConvertible,而Guid 没有。
【解决方案2】:

您可以使用 Guid.Parse() 或 Guid.TryParse()

content.ModifiedBy = Guid.Parse(User.Identity.GetUserId());

https://msdn.microsoft.com/en-us/library/system.guid.parse%28v=vs.110%29.aspx

由于我一遍又一遍地使用相同的方法,我添加了以下扩展:

 public static class ExtensionMethods
{
    public static Guid ToGuid(this string value)
    {
        Guid result= Guid.Empty;
        Guid.TryParse(value, out result);
        return result;          
    }
}

然后我用了这个:

User.Identity.GetUserId().ToGuid()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2019-09-15
    • 2014-07-28
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多