MVC implements dynamic two-level domain names

Source: Internet
Author: User
Tags httpcontext

Some time ago, a friend asked me the question of implementing a dynamic two-level domain name under ASP. Talked to him about some of the solutions, which are summarized here for reference.

I believe we all found similar to 58 of the same city site, Chengdu's website is cd.58.com Shanghai is sh.58.com similar to thousands of sites, in fact, there are not so many sites, domain name before that part is the pan-domain name resolution, equivalent to pass a parameter, all the domain name is actually access to a site, just pass the different parameters display different content.

For example, the main portal domain entry is: www.58.com
When the user logs in Chengdu, resolves to: cd.58.com
When a user in Shanghai logs in, it resolves to: sh.58.com

The first thing to think about is the rewrite of the URL: (This is also commonly used in ASP.) Online about the implementation of Urlrewrite, which is no longer repeated here. )

There is a typical URL pattern in an MVC application where only the dynamic two-level domain name implementation in the MVC application URL pattern is discussed, and the test instance is downloaded.

 1. Define Domaindata, Domainroute class

public class Domainroute:route
{
Private Regex Domainregex;
Private Regex Pathregex;

public string Domain {get; set;}

Public Domainroute (string domain, string url, routevaluedictionary defaults): Base (URL, defaults, new Mvcroutehandler ())
{
domain = domain;
}

Public Domainroute (string domain, string url, routevaluedictionary defaults, Iroutehandler routehandler): Base (URL, Defaults, Routehandler)

{
domain = domain;
}

Public Domainroute (string domain, string url, object defaults): Base (URL, new RouteValueDictionary (defaults), New mvcrout Ehandler ())
{
domain = domain;
}

Public Domainroute (string domain, string url, object defaults, Iroutehandler Routehandler): Base (URL, new routevaluedicti Onary (defaults), Routehandler)
{
domain = domain;
}

public override Routedata Getroutedata (HttpContextBase HttpContext)
{
Constructing a Regex
Domainregex = Createregex (Domain);
Pathregex = Createregex (URL);
Request Information
String requestdomain = httpcontext.request.headers["Host"];
if (!string. IsNullOrEmpty (Requestdomain))
{
if (Requestdomain.indexof (":") > 0)
{
Requestdomain = requestdomain.substring (0, Requestdomain.indexof (":"));
}
}
Else
{
Requestdomain = HttpContext.Request.Url.Host;
}
String Requestpath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring (2) + HttpContext.Request.PathInfo;

Matching domain names and routes
Match Domainmatch = Domainregex.match (Requestdomain);
Match Pathmatch = Pathregex.match (Requestpath);

Routing data
Routedata data = null;
if (domainmatch.success && pathmatch.success)
{
data = new Routedata (this, routehandler);
Add default Options
if (Defaults! = null)
{
foreach (keyvaluepair<string, object> item in Defaults)
{
Data. Values[item. Key] = Item. Value;
}
}

Matching domain name Routing
for (int i = 1; i < DomainMatch.Groups.Count; i++)
{
Group group = Domainmatch.groups[i];
if (group. Success)
{
String key = Domainregex.groupnamefromnumber (i);
if (!string. IsNullOrEmpty (key) &&!char. Isnumber (key, 0))
{
if (!string. IsNullOrEmpty (group. Value))
{
Data. Values[key] = group. Value;
}
}
}
}

Match the domain name path
for (int i = 1; i < PathMatch.Groups.Count; i++)
{
Group group = Pathmatch.groups[i];
if (group. Success)
{
String key = Pathregex.groupnamefromnumber (i);

if (!string. IsNullOrEmpty (key) &&!char. Isnumber (key, 0))
{
if (!string. IsNullOrEmpty (group. Value))
{
Data. Values[key] = group. Value;
}
}
}
}
}

return data;
}

public override Virtualpathdata GetVirtualPath (RequestContext requestcontext, routevaluedictionary values)
{
Return base. GetVirtualPath (RequestContext, Removedomaintokens (values));
}

Public Domaindata Getdomaindata (RequestContext requestcontext, routevaluedictionary values)
{
Get host Name
string hostname = Domain;
foreach (keyvaluepair<string, object> pair in values)
{
hostname = hostname. Replace ("{" + pair. Key + "}", pair. Value.tostring ());
}

Return Domain Name Data
return new Domaindata
{
Protocol = "http",
HostName = HostName,
Fragment = ""
};
}

Private Regex Createregex (string source)
{
Replace
Source = source. Replace ("/", @ "/?");
Source = source. Replace (".", @ "\.?");
Source = source. Replace ("-", @ "\-?");
Source = source. Replace ("{", @ "(?<");
Source = source. Replace ("}", @ "> ([a-za-z0-9_]*))");

return new Regex ("^" + source + "$", regexoptions.ignorecase);
}

Private RouteValueDictionary Removedomaintokens (RouteValueDictionary values)
{
Regex Tokenregex = new Regex (@ "({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/? ({[a-za-z0-9_]*}) *-?\.? \/?");
Match Tokenmatch = Tokenregex.match (Domain);
for (int i = 0; i < TokenMatch.Groups.Count; i++)
{
Group group = Tokenmatch.groups[i];
if (group. Success)
{
String key = group. Value.replace ("{", ""). Replace ("}", "");
if (values. ContainsKey (Key))
Values. Remove (key);
}
}

return values;
}
}
public class Domaindata
{
public string Protocol {get; set;}
public string HostName {get; set;}
public string Fragment {get; set;}
}
   2. Modify the Routeconfig to add the following code
Routes. ADD (
"Domainroute", New Domainroute (
"{citynameurl}.weiz.com",
"{Controller}/{action}/{id}",
New {Citynameurl = "", Controller = "City", action = "Index", id = ""}
));
   3. Add Citycontroller Control class
public class Citycontroller:controller
{
Public ActionResult Index ()
{
var cityname = routedata.values["Citynameurl"];
Viewbag.cityname = CityName;
return View ();
}
}

  4. Publish the website and modify the relevant configuration
Mode one: Modify the host, we modify the host file, to achieve a two-level domain name, only through an increase in parsing such as:
#host文件
127.0.0.1 www.weiz.com
127.0.0.1 a.weiz.com
127.0.0.1 b.weiz.com
127.0.0.1 c.weiz.com

Mode two: Increase the pan domain name resolution, configure the DNS service, that is, let your domain name support pan-resolution (Windows Server will have, other Windows system can only modify the attempt to modify the host file, easy to test) see my other article, "Domain name Pan-resolution settings"

  5. Effects

  

MVC implements dynamic two-level domain names

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.