ASP.NET Core 2-GetUserIdAsync返回带有Guid ID的空结果 [英] ASP.NET Core 2 - GetUserIdAsync returning null Result with Guid Ids
问题描述
我当前正在将网站移植到ASP.NET Core 2,并且当我使用扩展了 IdentityUser<的用户类调用
: userManager.GenerateEmailConfirmationTokenAsync(user)
时,引发了以下异常.Guid>
I'm currently porting a site to ASP.NET Core 2 and am getting the following Exception thrown when I call userManager.GenerateEmailConfirmationTokenAsync(user)
with a user class that extends IdentityUser<Guid>
:
System.ArgumentNullException: Value cannot be null.
Parameter name: value
at System.IO.BinaryWriter.Write(String value)
at Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1.<GenerateAsync>d__11.MoveNext()
GenerateAsync()
调用 UserManager.GetUserIdAsync()
,它在 Result
中返回 null
值,而 Write()
抱怨关于,即使我经过的 User
实例在 Id
中具有 07c0423e-f36b-1410-8007-800000000000
.
GenerateAsync()
makes a call to UserManager.GetUserIdAsync()
, which is returning the null
value in Result
, which Write()
is complaining about, even though the User
instance I'm passing through has 07c0423e-f36b-1410-8007-800000000000
in Id
.
如果我直接在调用 GenerateEmailConfirmationTokenAsync()
的同一个 UserManager
实例上直接调用 userManager.GetUserIdAsync(user)
在 Result
中使用相同的 null
值.
If I call userManager.GetUserIdAsync(user)
directly on the same UserManager
instance on which I'm calling GenerateEmailConfirmationTokenAsync()
I get this same null
value in Result
.
有人知道如何解决这个问题吗?
Does anyone have any ideas how to resolve this?
编辑:根据要求,可以在 github.com/上找到一个功能示例.BenjaminNolan/GetUserIdAsyncNullExample
Edit: As requested, a functional example can be found at github.com/BenjaminNolan/GetUserIdAsyncNullExample
推荐答案
The problem you have is with these lines from your User
class:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[DefaultValue("NEWSEQUENTIALID()")]
new public Guid Id { get; set; }
您使用新修饰符此处禁止显示以下编译器警告:
Your use of the new modifier here is suppressing the following compiler warning:
'User.Id'隐藏继承的成员'IdentityUser.Id'.
'User.Id' hides inherited member 'IdentityUser.Id'.
此警告通知您,如果您通过 User
引用(而不是例如 IdentityUser< Guid>
引用-基础)访问 Id
类),您将使用不同 Id
属性.如果在控制器中检查 user.Id
的值并将其与(((IdentityUser< Guid>)user).Id
>(广播到基类以访问其 Id
属性).
This warning informs you that if you access Id
via a User
reference (rather than e.g. a IdentityUser<Guid>
reference - the base class), you will be working with a different Id
property. You can see what this looks like if you inspect the value of user.Id
in your controller and compare that with the value of ((IdentityUser<Guid>)user).Id
(casting to the base class in order to access its Id
property).
很容易解决您的情况-只需从 User
类中删除 Id
属性:您已经指定了现有的 Id
IdentityUser< TKey> 中的>属性将是 Guid
类型,并且其已配置为密钥,等等.
It's easy to fix in your case - just remove the Id
property from your User
class: you've already specified that the existing Id
property from IdentityUser<TKey>
will be of type Guid
and its already configured to be the key, etc.
这篇关于ASP.NET Core 2-GetUserIdAsync返回带有Guid ID的空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!