Can Areas in an ASP.NET MVC 2 application map to a subdomain?

后端 未结 4 1486
攒了一身酷
攒了一身酷 2021-02-04 03:10

Is there a way to map the Areas within an ASP.NET MVC 2 application to subdomains such as

movies.example.com/Theater/View/2

instead of

4条回答
  •  有刺的猬
    2021-02-04 03:25

    I've tried a lot of the solutions mentioned on other threads and found things getting too complicated very quickly. It seems like ASP.Net MVC wants you to sub-class Route to do this kind of advanced routing, but it never seemed to work for me. I was never able to get a domain to map to a namespace, so I wound up with "ambiguous controller" exceptions (since I had a home controller in both namespaces).

    Ultimately I used a constraint to point sub-domains to namespaces.

    Here's what my route looks like. Notice that this route is for the "api." sub-domain:

            context.MapRoute(
                "Api_Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                new { controller = new SubdomainRouteConstraint("api.") },
                new[] { "BendyTree.CloudSpark.Areas.Api.Controllers" }
                );
    

    Here's the "SubdomainRouteConstraint" class referenced above:

    public class SubdomainRouteConstraint : IRouteConstraint
    {
        private readonly string SubdomainWithDot;
    
        public SubdomainRouteConstraint(string subdomainWithDot)
        {
            SubdomainWithDot = subdomainWithDot;
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return new Regex("^https?://" + SubdomainWithDot).IsMatch(httpContext.Request.Url.AbsoluteUri);
        }
    }
    

    It's obviously quite a hack, but I'm really happy with how simple it ended up.

    You could easily tweek this code to dynamically map a subdomain to an area, but I only have two areas so I just register each area separately. Plus this gives me the freedom to have different routing inside each area.

提交回复
热议问题