代码之家  ›  专栏  ›  技术社区  ›  Khalil Liraqui

使用者身份GetUserId()在构造函数中返回null

  •  1
  • Khalil Liraqui  · 技术社区  · 8 年前

    使用者身份GetUserId()在控制器构造函数中返回null 这是我的表格:

    @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.ValidationSummary("", new { @class = "text-danger" })
        @Html.AntiForgeryToken()
    
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", placeholder = "Email" })         
        @Html.PasswordFor(m => m.Password, new { @class = "form-control", placeholder = "Mot de passe" })
    
        <input type="submit" id="ModalSubmitButton" class="btn btn-primary btn-lg btn-block login-button" value="Se connecter" />
    }
    

    然后在account Controller中的登录操作中:

    [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
                    switch (result)
                    {
                        case SignInStatus.Success:
                            //return RedirectToLocal(returnUrl);
                            return RedirectToAction("Index", "User");
                        case SignInStatus.LockedOut:
                            return View("Lockout");
                        case SignInStatus.RequiresVerification:
                            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                        case SignInStatus.Failure:
                        default:
                            ModelState.AddModelError("", "Tentative de connexion non valide.");
                            return PartialView("_SignIn",model);
                    }
    

    在userController构造函数中,我有:

    public ActionResult Index()
            {
                var x = User.Identity.GetUserId();
                return View();
            }
    

    更新:我使用Int作为ID,而不是string

    1 回复  |  直到 8 年前
        1
  •  3
  •   Zahid Tanveer    8 年前

    检索当前登录的用户UserID

    using Microsoft.AspNet.Identity;
    

    在控制器构造函数中使用:

    System.Web.HttpContext.Current.User.Identity.GetUserId();
    

    而不是在控制器动作方法中使用:

    var userId = User.getUserId();
    

    因为在构造函数中无法获取当前用户。默认情况下,您需要显式指定标识。

    推荐文章