ASP.NET MVC Subdomains

后端 未结 3 1446
渐次进展
渐次进展 2020-12-28 09:18

I have hosting and domain like that:

www.EXAMPLE.com

I\'ve created few subdomains like that:

www.PAGE1.EXAMPLE.com
www.PAGE         


        
3条回答
  •  旧时难觅i
    2020-12-28 10:05

    You can do this by writing a custom Route. Here's how (adapted from Is it possible to make an ASP.NET MVC route based on a subdomain?)

    public class SubdomainRoute : RouteBase
    {
    
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var host = httpContext.Request.Url.Host;
            var index = host.IndexOf(".");
            string[] segments = httpContext.Request.Url.PathAndQuery.Split('/');
    
            if (index < 0)
                return null;
    
            var subdomain = host.Substring(0, index);
            string controller = (segments.Length > 0) ? segments[0] : "Home";
            string action = (segments.Length > 1) ? segments[1] : "Index";
    
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", controller); //Goes to the relevant Controller  class
            routeData.Values.Add("action", action); //Goes to the relevant action method on the specified Controller
            routeData.Values.Add("subdomain", subdomain); //pass subdomain as argument to action method
            return routeData;
        }
    
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            //Implement your formating Url formating here
            return null;
        }
    }
    

    Add to the route table in Global.asax.cs like this:

    routes.Add(new SubdomainRoute());
    

    And your controller method:

    public ActionResult Index(string subdomain)
    {
        //Query your database for the relevant articles based on subdomain
        var viewmodel = MyRepository.GetArticles(subdomain);
        Return View(viewmodel);
    }
    

提交回复
热议问题