I have many host names on IIS that point to the same ASP.NET MVC app.
www.domain.com
www.domain.co.uk
www.domain.net
...
How can I get the top level domain (es. ".com") when I set a map route like the following?
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
' MapRoute takes the following parameters, in order:
' (1) Route name
' (2) URL with parameters
' (3) Parameter defaults
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
End Sub
You need to create a custom route. Just inherit Route
, override GetRouteData
and include routing information which is for the TLD.
http://msdn.microsoft.com/en-us/library/system.web.routing.route.getroutedata.aspx
Example
The route:
public class RouteWithTld : Route
{
public RouteWithTld(string url, IRouteHandler routeHandler) : base(url, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var baseData = base.GetRouteData(httpContext);
int pos = httpContext.Request.Url.Host.LastIndexOf('.');
string tld;
if (pos == -1)
{
if (httpContext.Request.Url.Host == "localhost")
tld = "com";
else
{
throw new InvalidOperationException("You need to handle this case.");
}
}
else
tld = httpContext.Request.Url.Host.Substring(pos + 1);
baseData.Values.Add("tld", tld);
return baseData;
}
}
Mapping it in global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
/*routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
* */
var defaults =
new RouteValueDictionary(new {controller = "Home", action = "Index", id = UrlParameter.Optional});
routes.Add(new RouteWithTld("{controller}/{action}/{id}", defaults, new MvcRouteHandler()));
}
And accessing the parameter in the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC. TLD: " + RouteData.Values["tld"];
return View();
}
public ActionResult About()
{
return View();
}
}