ASP.NET 5 MVC6 User.GetUserId() returns incorrect

2019-04-09 13:52发布

问题:

I have simple project in ASP.NET 5 with one registered user. I have tried to get id of current logged user by extension method GetUserId() from using System.Security.Claims namespace. Unfortunately this method returns me not existing id and i don't know why.

Here is my simple code:

var currentUserId = User.GetUserId();

Method result:

Database:

回答1:

More than likely you're getting an old auth ticket that is still valid OR your getting an authentication ticket for another site your running locally. I would clear the browser cache and cookies and run it again.

Also, Try changing the name of the cookie, by default it is set to .AspNet.Cookies which can cause issues if you're running multiple apps locally. This caught me up a while back.

The cookie name can be changed like this

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",
});

The MSDN documentation on it can be found here.