繁体   English   中英

如何让当前用户登录我的 AspNet 项目?

[英]How to get the current user logged in my AspNet project?

我创建了一个简单的 AspNet 项目(.net 框架),成功登录后我进入了主页。

如果我点击“Hello mail@mail.it!” 按钮 我可以访问 Manage 方法并获取我当前的User.Identity.Name (即我的 mail@mail.it),因为我的UserMangerSignInManager已填充。 相反,如果我尝试访问 ApiController 中的另一个方法并检索 User.Identity.Name,则 UserManger 和 SignInManager 为空,我的名字为null

那是我的 ApiController:

namespace NameSpace.Controllers.API
{     
    public class LoginController : ApiController
    {
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;

        public LoginController()
        {
        }


        public LoginController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }

        public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.Current.Request.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
            }
            private set
            {
                _userManager = value;
            }
        }

        [HttpGet]
        public HttpResponseMessage Check()
        {
            var username = User.Identity.Name;
            if(username != null){
                return Request.CreateResponse(HttpStatusCode.OK, username );
            }
        }

    }

}

是否有我遗漏的东西,或者还有其他地方可以找到当前用户?

您可以尝试使用以下方法:

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
   string username = System.Web.HttpContext.Current.User.Identity.Name;
}

更新:

尝试以下操作来获取 http 上下文:

// get httpContext here

object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM