-
-
Save solrevdev/ea365dc39778e40681175731f147f833 to your computer and use it in GitHub Desktop.
A class to detect the subdomain and pass it through as a route parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class SubdomainRoute : RouteBase | |
| { | |
| public override RouteData GetRouteData(HttpContextBase httpContext) | |
| { | |
| if (httpContext.Request == null || httpContext.Request.Url == null) | |
| { | |
| return null; | |
| } | |
| var host = httpContext.Request.Url.Host; | |
| var index = host.IndexOf("."); | |
| string[] segments = httpContext.Request.Url.PathAndQuery.TrimStart('/').Split('/'); | |
| if (index < 0) | |
| { | |
| return null; | |
| } | |
| var subdomain = host.Substring(0, index); | |
| string[] blacklist = { "www", "yourdomain", "mail" }; | |
| if (blacklist.Contains(subdomain)) | |
| { | |
| return null; | |
| } | |
| 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment