Как получить доступ к HttpContext за пределами контроллеров в ASP.NET MVC?

А именно, Переменные сеанса. У меня есть .ashx в моем проекте MVC ASP.NET, который вытягивает некоторые данные изображения для отображения пользователю, и я должен смочь получить доступ к объекту, который я хранил на сессии. От контроллеров я могу вытянуть объектный штраф, но на моей ashx странице, контексте. Сеанс является пустым. Какие-либо мысли?Спасибо!

Вот пример того, что я пытаюсь сделать... контекст. Сессия всегда возвращает пустой указатель.

  private byte[] getIconData(string icon)
    {
        //returns the icon file
        HttpContext context = HttpContext.Current;

        byte[] buffer = null;

        //get icon data
        if ( context.Session["tokens"] != null)
        {
            //do some stuff to get icon data
        }
    }
18
задан DaveRandom 25 February 2013 в 20:41
поделиться

2 ответа

Ok, so what I ended up having to do.... in my ashx file, I added in the IReadOnlySessionState interface and it will access the session state just fine. So it looks something like this...

  public class getIcon : IHttpHandler, IReadOnlySessionState
2
ответ дан 30 November 2019 в 08:15
поделиться

You must import the System.Web assembly in your code and then you can do something like this:

HttpContext context = HttpContext.Current;

return (User)context.Session["User"];

Editing:

Dude, I did some tests here and it works for me, try something like this:

Create a helper class to encapsulate you getting session variables stuff, it must import the System.Web assembly:

public class TextService
    {
        public static string Message { 
            get 
            { 
                HttpContext context = HttpContext.Current; 
                return (string)context.Session["msg"]; 
            }
            set
            {
                HttpContext context = HttpContext.Current;
                context.Session["msg"] = value;
            }
        }
    }

Then in your controller you should do something like:

TextService.Message = "testing the whole thing";
return Redirect("/home/testing.myapp");

And in your other classes you can call the helper class:

return TextService.Message;

Give it a try.

23
ответ дан 30 November 2019 в 08:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: