Request.IsAuthenticated 在控制器基类中抛出 NullReferenceException

本文关键字:NullReferenceException 基类 IsAuthenticated 控制器 Request | 更新日期: 2023-09-27 17:56:24

我创建了一个自定义控制器类,并使用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]);
        }
    }

Request.IsAuthenticated 在控制器基类中抛出 NullReferenceException

你所需要的只是System.Web.HttpContext

public JekController() : base()
{
    ...
    if(!System.Web.HttpContext.Current.Request.IsAuthenticated)
    {
        LoginService.SignInFromAuthCookie(Request.Cookies[FormsAuthentication.FormsCookieName]);
    }
}

我解决了以下问题:http://www.dotnetfunda.com/forums/show/18457/requestuser-object-is-null-in-controller-constructor-in-aspnet-mvc

您需要重写 Initialize() 方法并检查会话:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    if (requestContext.HttpContext.User.Identity.IsAuthenticated)
    {
        //do something
    }
}