如何在Identity 3.0中获取当前的UserId? User.GetUserId返回null [英] How to get current UserId in Identity 3.0? User.GetUserId returns null
问题描述
我需要获取发出某些请求的用户的ID. 在以前的Identity版本中,我可以这样:
I need to get ID of user that made some request. In previous versions of Identity I could do it like this:
User.Identity.GetUserId();
但是它似乎不再可用.
还有类似的东西:
User.GetUserId();
但是即使User.Identity.IsAuthenticated为true并且User.Identity.Name设置正确,它也始终返回null.
But it always returns null, even if User.Identity.IsAuthenticated in true and User.Identity.Name is set correctly.
我应该怎么做?
My authenticaton logic is based on [default Visual Studio 2015 template], I hadn't changed much so far in identity, so if you want to check how is it done, you can simply see it on github link I pasted.
推荐答案
在我们的讨论之后,您的用户身份似乎不包含User.GetUserId()使用的正确声明.
Following our discussion, it seems your user identity does not contain the correct claim used by User.GetUserId().
以下是您可以手动设置NameIdentifier声明的方法:
Here is how you can manually set the NameIdentifier claim:
// ClaimsIdentity identity = new ClaimsIdentity...
identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);
这篇关于如何在Identity 3.0中获取当前的UserId? User.GetUserId返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!