ASP.NET 5 MVC6 User.GetUserId() returns 不正确的 ID
ASP.NET 5 MVC6 User.GetUserId() returns incorrect id
我在 ASP.NET 5 中有一个简单的项目,只有一个注册用户。我试图通过扩展方法 GetUserId()
从 using System.Security.Claims
命名空间获取当前登录用户的 ID。
不幸的是,这种方法 returns 我没有现有的 ID,我也不知道为什么。
这是我的简单代码:
var currentUserId = User.GetUserId();
方法结果:
数据库:
很有可能您得到的是 旧 仍然有效的身份验证票证,或者您在本地 运行ning 获得了另一个站点的身份验证票证。我会清除浏览器缓存和 cookie,然后再次 运行。
此外,请尝试更改 cookie 的名称,默认情况下它设置为 .AspNet.Cookies
如果您在本地 运行 安装多个应用程序,这可能会导致问题。这引起了我的注意。
cookie名称可以这样改
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
},
CookieName = "myAuthCookie",
});
上面的MSDN文档可以found here.
我在 ASP.NET 5 中有一个简单的项目,只有一个注册用户。我试图通过扩展方法 GetUserId()
从 using System.Security.Claims
命名空间获取当前登录用户的 ID。
不幸的是,这种方法 returns 我没有现有的 ID,我也不知道为什么。
这是我的简单代码:
var currentUserId = User.GetUserId();
方法结果:
数据库:
很有可能您得到的是 旧 仍然有效的身份验证票证,或者您在本地 运行ning 获得了另一个站点的身份验证票证。我会清除浏览器缓存和 cookie,然后再次 运行。
此外,请尝试更改 cookie 的名称,默认情况下它设置为 .AspNet.Cookies
如果您在本地 运行 安装多个应用程序,这可能会导致问题。这引起了我的注意。
cookie名称可以这样改
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
},
CookieName = "myAuthCookie",
});
上面的MSDN文档可以found here.