为什么HttpContext.User.Identity.IsAuthenticated
将System.NullReferenceException
抛出到我所有其他控制器继承的基本控制器中?
我认为HttpContext
在我的基本控制器的构造函数中没有准备好。
这是代码:
public abstract class BasicController : Controller
{
private IUserProfileRepository _userProfileRepository;
protected BasicController()
: this(new UserProfileRepository())
{
}
protected BasicController(IUserProfileRepository userProfileRepository)
{
_userProfileRepository = userProfileRepository;
if (HttpContext.User.Identity.IsAuthenticated)
{
var user = _userProfileRepository.Getuser(HttpContext.User.Identity.Name);
ViewData["currentlyLoggedInUser"] = user;
}
else
{
ViewData["currentlyLoggedInUser"] = null;
}
}
HttpContext
未在基本控制器构造函数中准备好。所以这就是我所做的,现在它正常工作:
public abstract class BasicController : Controller
{
private IUserProfileRepository _userProfileRepository;
protected BasicController()
: this(new UserProfileRepository())
{
}
protected BasicController(IUserProfileRepository userProfileRepository)
{
_userProfileRepository = userProfileRepository;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var user = _userProfileRepository.Getuser(filterContext.HttpContext.User.Identity.Name);
filterContext.Controller.ViewData["currentlyLoggedInUser"] = user;
}
else
{
filterContext.Controller.ViewData["currentlyLoggedInUser"] = null;
}
}
}
答案 0 :(得分:1)
因为 HttpContext.User 尚未由任何身份验证模块设置。您是否要求此网站的经过身份验证的用户?您是否禁用了 DefaultAuthenticationModule ?或者可能是在AuthenticateRequest event of HttpApplication被触发之前创建了控制器实例?