Asp.net Identity 2 User.Identity.GetUserId <int>()总是返回0?

BBa*_*r42 1 asp.net-identity-2

我已经扩展了Asp.net Identity 2模型,通过跟随这样这样的帖子来使用整数键.但是,这行代码始终返回0.

User.Identity.GetUserId<int>()
Run Code Online (Sandbox Code Playgroud)

即使User.Identity.IsAuthenticated为true且User.Identity.GetUserName()返回正确的用户名.我已经看过这篇文章,但它没有帮助,因为我已经在控制器方法中调用User.Identity.GetUserId()而不是构造函数.该帖子中对"getUserIdCallback"的引用很有意思,也许我需要这样的东西.任何帮助深表感谢.

BBa*_*r42 7

事实证明,我需要在自定义OAuthAuthorizationServerProvider的GrantResourceOwnerCredentials方法中将用户的ID添加到ClaimsIdentity.这是方法:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

    if (user == null)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
    }

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    //THIS IS THE IMPORTANT LINE HERE!!!!!
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    identity.AddClaim(new Claim("sub", context.UserName));

    foreach (var role in userManager.GetRoles(user.Id))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, role));
    }

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        { "as:client_id", context.ClientId ?? string.Empty }
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}
Run Code Online (Sandbox Code Playgroud)