我创建了一个自定义控制器类,我使用cookie来记录标记“记住我”复选框的用户的曲目。
但是当我尝试访问Request.IsAuthenticated
时,为了查看用户是否拥有登录票证,它会抛出NullReferenceException
。我哪里错了?
我的代码:
public class JekController : Controller
{
...
public JekController()
: base()
{
LoginService = new LoginService();
TimeSheetService = new TimeSheetService();
if(!Request.IsAuthenticated) //NullReferenceException: Request is null
{
LoginService.SignInFromAuthCookie(Request.Cookies[FormsAuthentication.FormsCookieName]);
}
}
答案 0 :(得分:1)
您需要的只是System.Web.HttpContext
public JekController() : base()
{
...
if(!System.Web.HttpContext.Current.Request.IsAuthenticated)
{
LoginService.SignInFromAuthCookie(Request.Cookies[FormsAuthentication.FormsCookieName]);
}
}
答案 1 :(得分:0)
您需要覆盖Initialize()方法并检查会话:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
if (requestContext.HttpContext.User.Identity.IsAuthenticated)
{
//do something
}
}