Doug Doug - 4 years ago 115
C# Question

How can you keep a session across multiple subdomains in c# mvc?

A shopping cart application I'm working on jumps domain when it goes from the normal page into the submit-your-details page.

Long story short there are two copies of the application deployed: one server for the 'main' site and one server with an ev certificate running on https for the customer details (including payment; this is a PCI compliance issue).

My question is this:

When jumping from http://shop.domain -> https://secure.domain (and back, if the user browses back), how can I preserve the session?

Its trivial to pass cookies cross domain using JSONP, but I have no idea what to do with them on the remote side to 'reconnect' to the session.

I have read various things about rolling your own custom session provider, etc. etc. but I haven't found one that is more than just generic advice; certainly no examples of how this might be used to rejoin a session.

This is a for an MVC3 c# web app.

Answer Source

Problem with Session's is that they are kept in the same domain.

If you have the 2 applications in sub domains you can always append this to your web.config

<httpCookies domain=".domain.com"/>

and that will do the trick, but if the domains are completely different, the best way is always to roll out your own session provider or use an existing one, like SQL.

You can use for this any Caching System where instead of append variables into a session variable, you append them into the cache as key/value pair, you can always use a NoSQL alternative (plenty of free accounts out there so you can prototyping and make a proof of concept in order to roll out the final bits).

Memcached server is always a good alternative and Couchbase as the community version available for free.

The trick here is to do this:

Cache.AddObject(key + "UserInfo-name", "Bruno Alexandre");

where key could be a query string value appended in global.asax upon session_start

instead of this

Session["UserInfo-name"] = "Bruno Alexandre";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download