我想初始化_applicationUser对象在构造函数中在Asp.Net MVC,那为什么ApplicationUser总是在我的代码空
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private ApplicationDbContext _dbContext;
private ApplicationUser _applicationUser;
public ManageController()
{
_dbContext = new ApplicationDbContext();
_applicationUser = new ApplicationUser();
// the _applicationUser below is always null,
// Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
_applicationUser = _dbContext.Users.Find(User.Identity.GetUserId());
ViewBag.ProfilePhoto = new ProfilePhotoViewModel
{
ProfilePhoto = _applicationUser.ProfilePhoto
};
}
public ActionResult Account()
{
_applicationUser = _dbContext.Users.Find(User.Identity.GetUserId());
ViewBag.ProfilePhoto = new ProfilePhotoViewModel
{
ProfilePhoto = _applicationUser.ProfilePhoto
};
}
但如果我评论的_applicationUser和ViewBag在构造函数然后浏览直接/管理/账号一切正常
_applicationUser = _dbContext.Users.Find(User.Identity.GetUserId());
确实在账户工作(),但我不知道为什么它不会在构造区域
User.Identity.GetUserId()返回什么?调试101,始终确保一切都有你认为它应该有的价值。 –
由于httpcontext在控制器初始化时尚未可用。由于httpcontext是持有用户,那么用户尚不可用 – Nkosi
@Nkosi - 有趣...想知道我如何获得我的自定义授权属性中的上下文和用户声明!也在我的基础控制器构造函数。 'System.Web.HttpContext.Current.User' – Developer