5

我正在使用ASP.Net Identity 2,但很快希望在Identity 3變得更加穩定時更改爲Identity 3(任何人都知道這可能是什麼時候?)。下面是我的代碼示例:如何使Identity.GetUserId()返回Guid而不是字符串?

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

內容表存儲ModifedBy作爲唯一標識符和內容對象指定的Guid的數據類型爲ModifiedBy

當我看到了GetUserId(簽名)它返回一個串。

那麼我怎樣才能把用戶的用戶ID,並把它放到ModifiedBy這是一個Guid?

+0

這是因爲UserId不僅可以是guid,所以如果您確定只使用guid,則需要轉換自己。 Identity V3適用於ASP.NET 5,所以期待v3與新ASP.NET的同時發佈。 – trailmax 2015-04-06 10:31:48

回答

7

一個GUID可以接受字符串作爲構造

content.ModifiedBy =新的GUID(User.Identity.GetUserId());

+3

我會用這種方法。有一個通用版本'GetUserId ',但是它下面使用'Convert.ChangeType',它需要value參數來實現'Guid'不能實現的'IConvertible'。 – MotoSV 2015-04-05 18:18:06

3

可以使用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() 
相關問題