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" />
}
然后在帐户控制器的登录操作中:
[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();
}
当我重定向到HomeController时,我可以获得userID,但是当我重定向到UserController时,userId = null
更新:我使用Int作为ID而不是字符串
答案 0 :(得分:2)
检索当前登录的用户UserID
using Microsoft.AspNet.Identity;
在控制器构造函数中使用:
System.Web.HttpContext.Current.User.Identity.GetUserId();
而不是在控制器操作方法中使用它:
var userId = User.getUserId();
因为在构造函数中,默认情况下您无法获取当前的User.Identity,所以需要明确指定它。