2

Is there any way to use subdomains for areas, that in ASP.NET MVC really would work?

I saw many different approaches, but none of them are fully working with ASP.NET MVC infrastructure:

a) use RouteConstraint (like MVC 3 Subdomain Routing) - it helps asp.net mvc to choose right route, but does not solve url generation issue

b) defining custom route class: http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas or http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx, both have problems with url generation (second one provides HtmlHelper.ActioLink extension as a solution, but that is only fraction of what is needed - url's are constructed using Html.BeginForm, Ajax.BeginForm, Url.Action, etc. - too much changes to existing code base + nobody would guarantee, that newbie won't forget to use right extension + not sure if that would work with T4MVC).

c) using url rewrite rule:

 <rules>
    <rule name="SubDomain" stopProcessing="false">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(\w+)\.domain\.com$" />
      </conditions>
      <action type="Rewrite" url="{C:1}/{R:1}" />
    </rule>
  </rules>

So if user requests admin.domain.com, asp.net mvc understands that domain.com/admin. So far so good, problem is with this (I am using T4MVC actually, but here is example without it, not to scare those, who never used it):

<a href="@Url.Action("Index", "Home")">

This, according to my routing should go to domain.com, but it is giving exception "Cannot use a leading .. to exit above the top directory".

I guess it is like this because UrlAction tries to construct url using current url (which is domain.com/admin after rewrite) and that leads to failure. Also I think it is only one way - just for finding right area/controller/action, but not for generating right urls.

So question is, have anybody done it both ways (i mean routing to right area/controller/action and generating url's using standard helpers, like HtmlHelper, UrlHelper)?

Community
  • 1
  • 1
Giedrius
  • 8,430
  • 6
  • 50
  • 91

1 Answers1

0

1st you need to make your DNS setting.

write code in global.asax below

 public class SubdomainRoute : Route
{
    public SubdomainRoute(string url, object defaults)
        : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    { }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        var tokens = httpContext.Request.Url.Host.Split('.');
        if (tokens.Length > 1)
        {
            rd.Values["username"] = tokens[0];

        }
        return rd;
    }
}
Ram Khumana
  • 844
  • 6
  • 14