LifeAct
@LifeAct
Создаем и раскручиваем, не ставим на конвейер

Почему не работает Base Controller?

Всем привет!

Есть две задачи:
1) в сессии хранить объект пользователь, чтобы за его свойствами не делать запросы в БД. (Пользователей на сайте довольно много);
2) посредством базового контроллера отлавливать ошибки всех контроллеров

Имеется asp mvc 5 VS 2015

Что делаю:

Базовый контроллер:

namespace WEB.Controllers
{
    public class BaseController : Controller
    {


        private BusinessLayer.User.User _currentUser;
        public BusinessLayer.User.User CurrentUser
        {
            get
            {
                if (!Request.IsAuthenticated) return null;

                if (_currentUser != null) return _currentUser;

                //try to get it form Session first, if its not there -> create it and put in the session
                if (Session["CurrentUser"] == null)
                {
                    _currentUser = new UserManager().UserDetailed(User.Identity.Name);
                    
                    Session["CurrentUser"] = _currentUser;
                    return _currentUser;
                }
                else //set it to the local var for the multiple references in the calling code and return
                {
                    _currentUser = (BusinessLayer.User.User)Session["CurrentUser"];
                    return _currentUser;
                }
            }

            set
            {
                _currentUser = value;
                Session["CurrentUser"] = _currentUser;
            }
        }



    }
}


В Global.asax ловлю ошибки все:
protected void Application_Error(object sender, EventArgs e)
        {
            BusinessLayer.Extensions.Mailer mailerManager = new BusinessLayer.Extensions.Mailer();

            HttpContext ctx = HttpContext.Current;
            Exception ex = ctx.Server.GetLastError();
            ctx.Response.Clear();

            RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
            IController controller = new  WEB.Controllers.BaseController();  // Тут можно использовать любой контроллер, например тот что используется в качестве базового типа
            var context = new ControllerContext(rc, (ControllerBase)controller);

            var viewResult = new ViewResult();

            var httpException = ex as HttpException;
            if (httpException != null)
            {

               


                switch (httpException.GetHttpCode())
                {


                    case 404:
......


Далее любой контроллер, например:
...

namespace WEB.Controllers
{

    
    public class EventsController : BaseController
    {


 public ActionResult UserStream()
        {
            if (User.Identity.IsAuthenticated)
            {
                BusinessLayer.User.UserManager UM = new BusinessLayer.User.UserManager();
                ViewBag.EventsMain = UM.UserStream(CurrentUser.Id, 20);
                return View("UserStream");
            }            
            else { return View("UserStreamNA"); }            
        }
......


CurrentUser - NULL. Ставлю точку останова в базовом контролере, но туда не заходит процесс и естественно CurrentUser не инициализирован....

Что я упустил?
Спасибо.
  • Вопрос задан
  • 284 просмотра
Пригласить эксперта
Ответы на вопрос 1
Возможно причина в этом
... тип переменной сеанса должен быть типом .NET или сериализуемым типом ...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы