HttpContext.User.Identity.IsAuthenticated throwing System.NullReferenceException - PullRequest
1 голос
/ 26 ноября 2009

Почему 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;
        }
    }
}

1 Ответ

1 голос
/ 26 ноября 2009

Поскольку HttpContext.User не был установлен ни одним модулем аутентификации. Вы требуете аутентифицированных пользователей для этого сайта? Вы отключили DefaultAuthenticationModule ? Или, может быть, экземпляр контроллера создается до того, как будет запущено событие AuthenticateRequest HttpApplication ?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...