How to get user context during Web Api calls?

前端 未结 2 762
感情败类
感情败类 2020-12-09 17:27

I have an web front end calling an ASP Web Api 2 backend. Authentication is managed with ASP Identity. For some of the controllers I\'m creating I need to know the user maki

2条回答
  •  再見小時候
    2020-12-09 17:59

    A common approach is to create a base class for your ApiControllers and take advantage of the ApplicationUserManager to retrieve the information you need. With this approach, you can keep the logic for accessing the user's information in one location and reuse it across your controllers.

    public class BaseApiController : ApiController
    {
            private ApplicationUser _member;
    
            public ApplicationUserManager UserManager
            {
                get { return HttpContext.Current.GetOwinContext().GetUserManager(); }
            }
    
            public string UserIdentityId
            {
                get
                {
                    var user = UserManager.FindByName(User.Identity.Name);
                    return user.Id; 
                }
            }
    
            public ApplicationUser UserRecord
            {
                get
                {
                    if (_member != null)
                    {
                        return _member ; 
                    }
                    _member = UserManager.FindByEmail(Thread.CurrentPrincipal.Identity.Name); 
                    return _member ;
                }
                set { _member = value; }
            }
    }
    

提交回复
热议问题