[英]User.Identity.GetUserId() returns null in cotrollers constructor
User.Identity.GetUserId() returns null in controller contructor this is my form : User.Identity.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" />
}
Then in the login action in 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);
}
And in the userController constructor i have : 在userController构造函数中,我有:
public ActionResult Index()
{
var x = User.Identity.GetUserId();
return View();
}
when i redirect to HomeController i can get the userID but when i redirect to UserController the userId = null 当我重定向到HomeController时,我可以获得用户ID,但是当我重定向到UserController时,userId = null
Update : i'm using Int as ID instead of string 更新:我使用Int作为ID而不是字符串
Retrieve current logged in user UserID 检索当前登录的用户UserID
using Microsoft.AspNet.Identity;
In controller constructor use this: 在控制器构造函数中使用以下命令:
System.Web.HttpContext.Current.User.Identity.GetUserId();
Instead of this is used in controller Action Method: 代替此方法的是控制器的“操作方法”:
var userId = User.getUserId();
Because in constructor you can't get the current User.Identity by default you need to specify it explicitly. 因为在构造函数中,默认情况下无法获取当前的User.Identity,因此需要显式指定它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.