Malin Malin - 2 months ago 5x
ASP.NET (C#) Question

Change default session provider in ASP.NET

I want to change my session proviced to statically typed - I just hate typing strings because of many many errors I do.

What technology am I using? ASP.NET MVC via EXT.NET MVC

I was trying to do that using web.config but the problem is that after add session state to it visual is not going to compile my code because of that session should be using strings as keys.

I want to use session by enums such as :

public enum SessionEnum{Model}
public class Bar{
void foo(){
Session[SessionEnum.Model] = "blah";

I am aware that I can create wrapper converting enums to strings but it's not very satisfying solution for me.

public class StorageWrapper{
public object this[SessionEnum enum]{ get{return Session[enum.toString()]}; //+set

What I did was create static object for base class for all of my controllers and then I was able to use it across them but after closing and opening the page again I wasn't able to get values from it. I guess I should serialize them somehow but I have no idea how.

Is there any way to do that?

My session now looks like this :

public abstract class DataWrapper<T> : HttpSessionStateBase
Dictionary<T, object> Dictionary { get; set; } = new Dictionary<T, object>();
public object this[T a]
return Dictionary[a];
return null;
set { Dictionary[a] = value; }
public class SessionWrapper : DataWrapper<SessionNames>
public enum SessionNames { Model, Login, LastOpenedFile }


It's very simple. Create a UserSession object which does everything you want (holds your values as enum etc), instantiate it, then put it in the session.

var US = new UserSession();
US.stuff = somestuff;
Session["UserSess"] = US

Then you can just always use Session["UserSess"].stuff;