I've wrote a post on how I use subdomain routing in my application. The source code is available on the post, but I'll try to explain how I did my custom RouteLink method.
The helper method uses the RouteTable
class to get the Route
object based on the current Url and cast it to a SubdomainRoute
object.
In my case all routes are defined using the SubdomainRoute and everytime I need to add a link to some other page I use my custom RouteLink helper, this is why I consider this cast safe. With the SubdomainRoute variable available I'm able to get the subdomain name and then build the Url using the UriBuilder class.
This is the code I'm currently using.
public static IHtmlString AdvRouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, object routeValues, object htmlAttributes)
{
RouteValueDictionary routeValueDict = new RouteValueDictionary(routeValues);
var request = htmlHelper.ViewContext.RequestContext.HttpContext.Request;
string host = request.IsLocal ? request.Headers["Host"] : request.Url.Host;
if (host.IndexOf(":") >= 0)
host = host.Substring(0, host.IndexOf(":"));
string url = UrlHelper.GenerateUrl(routeName, null, null, routeValueDict, RouteTable.Routes, htmlHelper.ViewContext.RequestContext, false);
var virtualPathData = RouteTable.Routes.GetVirtualPathForArea(htmlHelper.ViewContext.RequestContext, routeName, routeValueDict);
var route = virtualPathData.Route as SubdomainRoute;
string actualSubdomain = SubdomainRoute.GetSubdomain(host);
if (!string.IsNullOrEmpty(actualSubdomain))
host = host.Substring(host.IndexOf(".") + 1);
if (!string.IsNullOrEmpty(route.Subdomain))
host = string.Concat(route.Subdomain, ".", host);
else
host = host.Substring(host.IndexOf(".") + 1);
UriBuilder builder = new UriBuilder(request.Url.Scheme, host, 80, url);
if (request.IsLocal)
builder.Port = request.Url.Port;
url = builder.Uri.ToString();
return htmlHelper.Link(linkText, url, htmlAttributes);
}
private static IHtmlString Link(this HtmlHelper htmlHelper, string text, string url, object htmlAttributes)
{
TagBuilder tag = new TagBuilder("a");
tag.Attributes.Add("href", url);
tag.InnerHtml = text;
tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}