Saturday 8 August 2009

ASP.NET MVC: Mini CMS Project - adding the domain and sub domain to the route data

This is step 1 of many in my plan to build a mini CMS in ASP.NET MVC to support an array of personalised sites hosted on http://cloud9sites.com. My requirement is for a really lightweight CMS that can be achieved by using a finite set of page templates (rather than having to support a page layout designer) and numerous combinations of stylesheets (largely derived from http://ui.jquery.com theme roller) and layouts offered up on the aspnet gallery http://www.asp.net/mvc/gallery
 
 
The implementation is identical (so I won't go into detail), but in short the following class needs to be added to global.asax and the custom DomainRoute needs to be added to the route table.This code is only slightly modified from the original to meet my needs. I simply want to pass the domain and sub domain to the controller so that I can decide at runtime which master page, CSS and scripts needs to be loaded for the request domain (and optionally sub domain).
 
 
 
public class DomainRoute : RouteBase

{

public override RouteData GetRouteData(HttpContextBase httpContext)

{

RouteData returnValue = null;

// Retrieve the url - and split by dots:

var url = httpContext.Request.Headers["HOST"];

// Determine if a subdomain is provided:

var index = url.IndexOf(".");

returnValue =

new RouteData(this, new MvcRouteHandler());

returnValue.Values.Add(

"controller", "Home");

returnValue.Values.Add(

"action", "Index");

string domain = url.Substring(index+1);

returnValue.Values.Add(

"domain", domain);

if (index < 0)

{

returnValue.Values.Add(

"subDomain", null);

}

else

{

string subDomain = url.Substring(0, index);

returnValue.Values.Add(

"subdomain", subDomain); }

return returnValue;

}

/// <summary>

/// Required override. Just return null ;)

/// </summary>

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)

{

return null;

}

}

No comments: