User.Identity.GetUserId() returns null in controller contructor this is my form :
@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 :
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
Update : i'm using Int as ID instead of string
Retrieve current logged in user 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.