-1

What is the best way to persist a unique id on a browser session in MVC.NET?

Is there some session/cookie ID value by default?

In my Global.asax, I could create a new Session["ID"] and use its ID property.

There's got to be another way?

I tried using

var session = HttpContext.Current.Session;
UserResearch userResearch = new UserResearch();
userResearch.SessionID = sesstion.SessionID.ToString();

But i get an error:

System.NullReferenceException: Object reference not set to an instance of an object

I need to pull initial browser and clicking research based on a user that hasnt logged in to anything, so i need some way to refer to them, hence the id.

I could create a unique id on the sql end and store it in a session, just seems like there should be a more straight forward way.

Is there a browser session id?

Pinch
  • 4,009
  • 8
  • 40
  • 60

2 Answers2

1

Your problem most likely is caused by where in the code you are trying to access HttpContext, this is why your getting a NullReference for Session. But assuming you get that worked out this is how I'd approach your problem.

I would just store a GUID in a cookie, then Get/Set it like so: (Untested)

public Guid SessionGUID(){
    if(HttpContext.Current.Request.Cookies["SessionGUID"])
    {
        //return the SessionGUID
        return HttpContext.Current.Request.Cookies["SessionGUID"].value as Guid;
    }
    else//new visit
    {
        //set cookie to a new random Guid
        var _guid=Guid.NewGuid();
        HttpCookie guidCookie = new HttpCookie("SessionGUID"); 
        guidCookie.Value = _guid;
        guidCookie.Expires = DateTime.Now.AddDays(1d);
        HttpContext.Current.Response.Cookies.Add(guidCookie);
        return _guid;
    } 
}
Kaizen Programmer
  • 3,798
  • 1
  • 14
  • 30
0

As per https://stackoverflow.com/users/374310/igor: thanks! global.asax is a file, class MvcApplication inside it may implement several methods/event handlers, some of those are called when Session is not available yet. Session_Start should work for you.

var session = HttpContext.Current.Session;
UserResearch userResearch = new UserResearch();
userResearch.SessionID = sesstion.SessionID.ToString();

I put it in Session Start and Voila!

Community
  • 1
  • 1
Pinch
  • 4,009
  • 8
  • 40
  • 60