Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C#

Get an unique session in each browser tab

Rate me:
Please Sign up or sign in to vote.
4.70/5 (3 votes)
17 Feb 2012LGPL3 86K   14   12
Get an unique session in each browser tab

I got a lot to do at work, hence the silence. I got a lot to blog about, but so little time ;/ I found an interesting question at Stackoverflow which this answer is for (also to show you that the blog is not forgotten).

A user wanted to store browser tab specific data which can be a problem since most browsers share a session between different tabs. The solution is to create a new route which generates a GUID and then use that guid to fetch and store session information. Keep in mind that you need two routes: one that works for users which just surfed into the site, and one that loads an existing guid.

Here is the route class:

C#
public class GuidRoute : Route
{
    private readonly bool _isGuidRoute;

    public GuidRoute(string uri, object defaults)
        : base(uri, new RouteValueDictionary(defaults), new MvcRouteHandler())
    {
        _isGuidRoute = uri.Contains("guid");

        DataTokens = new RouteValueDictionary();
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData == null)
            return null;

        if (!routeData.Values.ContainsKey("guid") || 
        routeData.Values["guid"].ToString() == "")
            routeData.Values["guid"] = Guid.NewGuid().ToString("N");

        return routeData;
    }

    public override VirtualPathData GetVirtualPath
    (RequestContext requestContext, RouteValueDictionary values)
    {
        return !_isGuidRoute ? null : base.GetVirtualPath(requestContext, values);
    }
}

Replace the default route in global.asax with it:

C#
/*routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional } // Parameter defaults
);*/

routes.Add("Default", new GuidRoute(
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", 
        guid = "", id = UrlParameter.Optional }));

routes.Add("GuidRoute", new GuidRoute(
    "g/{guid}/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", 
        guid = "", id = UrlParameter.Optional }));

And finally some extension methods to make life easier in the controllers:

C#
public static class ControllerExtensionMethods
{
    public static string GetGuid(this Controller controller)
    {
        return controller.RouteData.Values["guid"].ToString();
    }

    public static void SetGuidSession
    (this Controller controller, string name, object value)
    {
        controller.Session[controller.GetGuid() + "_" + name] = value;
    }

    public static object GetGuidSession(this Controller controller, string name)
    {
        return controller.Session[controller.GetGuid() + "_" + name];
    }
}

One thing left though: Any browser bookmarks will use an old GUID. Should not be a problem in most cases (unless the user opens the bookmark in multiple tabs = sharing the session between the tabs). Same thing goes for opening a link in a new tab = shared.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Founder 1TCompany AB
Sweden Sweden

Comments and Discussions

 
QuestionHow to set route for images Pin
reddiamond_pilani12-May-17 21:02
reddiamond_pilani12-May-17 21:02 
Hi jgauffin,

Thankyou very much for such a good article.
I implemented it successfully, but now I am facing the issue that the route for all the images is not found. For every image it gives this error
The controller for path '/g/67aba8a5f6904ee3a208f245ecfddac7/Content/images/cal.png' was not found or does not implement IController.


Can you please suggest into this.

Thanking you in advance
Heeralal
QuestionControllerExtensionMethods Pin
Member 123667452-Mar-16 23:56
Member 123667452-Mar-16 23:56 
QuestionRe: ControllerExtensionMethods Pin
Member 102330995-Jan-17 4:52
Member 102330995-Jan-17 4:52 
GeneralAdd code sample project if you have Pin
smilanshah25-Jan-16 2:28
smilanshah25-Jan-16 2:28 
QuestionNamespace Pin
MicheleLaPietra30-Mar-15 5:27
MicheleLaPietra30-Mar-15 5:27 
Generalguid appending URL Pin
asp.anjan21-Jun-13 16:29
asp.anjan21-Jun-13 16:29 
GeneralRe: guid appending URL Pin
jgauffin9-Sep-13 2:55
jgauffin9-Sep-13 2:55 
GeneralRe: guid appending URL Pin
Member 1098130511-Sep-19 6:52
Member 1098130511-Sep-19 6:52 
QuestionOpen new tab for new session? Pin
cmr_nz19-Aug-12 17:04
cmr_nz19-Aug-12 17:04 
GeneralMy vote of 5 Pin
Sandeep Mewara18-Jul-12 22:57
mveSandeep Mewara18-Jul-12 22:57 
GeneralMy vote of 3 Pin
Dean Oliver22-Feb-12 8:41
Dean Oliver22-Feb-12 8:41 
GeneralRe: My vote of 3 Pin
jgauffin23-Feb-12 0:32
jgauffin23-Feb-12 0:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.