views:

460

answers:

2

I have searched for examples and found several but they are whole large projects. I am looking for some sample on how to get started building an MVC multi-tenant application. I think, the first part would be to decipher the url.

In ASP.Net this is how I did it. I got this from looking at DNN code. How would I do the same in MVC?

Global.asax

private void Application_BeginRequest(Object source, EventArgs e)
{
  HttpApplication application = (HttpApplication)source;
  HttpContext context = application.Context;

  string domainName = string.Empty;
  // domaName now contains 'example' if application.Request was www.example.com
  domainName = GetDomainName(application.Request);

  // Using domain, get the info for example from the database
  object myPortal = // get from database
  // Save in context for use on other pages
  context.Items.Add("PortalSettings", myPortal);
}

Then in my basepage I get the value from the context.

+1  A: 
  1. Get the domain name. You are on the right track with the DNN code. Just poke around the Request static variable in the debugger; there's all kinds of cool stuff there.
  2. You'll probably need a user store. I use a use a custom database, but you could use the Microsoft membership provider and profile provider. Make the domain a property of the user, or a property of an organization, and the organization a property of the user.
  3. Store the user's domain in the cookie, encrypted. Read the cookie at the beginning of the request, and make user the user has access to that org/domain.
  4. Make a BaseController that extends Controller, then have all your controllers inherit from it. In the BaseController, override OnActionExecuting. This is a much easier place to do your initial request rigging than the Global.asax.cs's Begin_request, because you can define protected members which will be available form every controller.
Josh Pearce
+2  A: 

I think an even more robust means would be to define a custom route. In that custom route is where you extract the domain and put it into the route values.

You then can have the base controller (as Josh described) which defines a Domain property or the like and stores that value there for convenience (or just extracts it on demand; either way).

By pulling it into the route values up front like that, you can make use of that information anywhere in the app along the request path, not just in the controller, so you get more re-use out of it that way. You can, for example, make use of it in a custom Authorize-like filter to handle the user's rights to that domain, and so on.

Paul
Paul, do you know of any sites with sample code of what you are suggesting? Thanks
Picflight
No, but custom routes are documented well in every MVC book that I've looked at. I'll try and find something.
Paul