don
don

Reputation: 113

How I use session in static funcs in mvc 6

this line not working

System.Web.HttpContext.Current.Session.RemoveAll();

Severity Code Description Project File Line Source Suppression State Error CS0234 The type or namespace name 'Web' does not exist in the namespace 'System' (are you missing an assembly reference?) MVC6.DNX Core 5.0 26

Edited

i created this

 public class MySession
    {
        private  readonly IHttpContextAccessor _httpContextAccessor;
        private  ISession _session => _httpContextAccessor.HttpContext.Session;

        public  MySession(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public  void Set(string key,object o)
        {
            _session.Set(key,o);
        }

        public  void Get(string key)
        {
            var message = _session.GetString(key);
        }
    }

  public static class SessionEx
    {
        public static void Set(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);

            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

How i use the set of session method from static func

  public static class SessionHandler
    { 
       public static void SetSessionId(long? id)
        {
          new MySession().Set("id", id);
        }
}

Upvotes: 1

Views: 391

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31193

The session system has been completely rewritten. In normal controllers you could just use HttpContext.Session, but if you need it elsewhere you need to inject it with IHttpContextAccessor.

Check this blog post for more information.

Upvotes: 1

Related Questions