在 ASP.Net Webforms Web api 中获取当前用户的 IdentityUser FullName

Get IdentityUser FullName of the current User in ASP.Net Webforms Web api

大家好,我的模型中有这个:

   public class ApplicationUser : IdentityUser
    {
        public string FullNamme { get; set; }


        public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            return Task.FromResult(GenerateUserIdentity(manager));
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

在我的控制器中我使用: string userId=HttpContext.Current.User.Identity.GetUserId(); 获取当前用户的 ID,但是如何获取当前用户的 属性 全名,请您帮忙。

使用 Identity,您应该使用 UserManager class 进行此类操作。默认的 MVC 模板还将创建它自己的继承版本,称为 ApplicationUserManager,因此假设您没有 removed/changed:

var userId = HttpContext.Current.User.Identity.GetUserId();
var userManager = ApplicationUserManager.Create();
var user = await userManager.FindByIdAsync(userId);
string fullName = user.FullName;

您可以使用 Owin 上下文管理器在任何地方获取用户管理器对象。在用户管理器的帮助下,您可以通过 ID 获取用户对象:

//make sure you added this line in the using section
using Microsoft.AspNet.Identity.Owin

string fullname = HttpContext.Current.GetOwinContext()
    .GetUserManager<ApplicationUserManager>()
    .FindById(HttpContext.Current.User.Identity.GetUserId()).FullName;