How to Create Dynamic Sub-domain with ASP.NET?

2019-03-16 21:55发布

问题:

How can I create a subdomain in an asp.net C# application? I am working with an asp.net portal.

I have my site which redirects all *.domain.com calls to domain.com. What I want to acheive is that first when the user enters a dynamic subdomain name he should be directed to its home page like if user writes www.microsite1.domain.com, then the site should point to page ~/Microsite/Home.aspx?value=microsite1, and when the user accesses www.microsite1.domain.com/about.aspx then i should able to get the argument value1=about.

回答1:

The first step is to place the subdomain name in the DNS Host Server. To do that you need to manipulate the dns files. For example if you use BIND as DNS server you go and open the text file that keep your DNS configuration eg: "c:\program files\dns\var\mysite.com" and there you add a line as

subdomain.mysite.com.   IN  A   111.222.333.444

Also you change the ID of the file to give a message to BIND to update the subdomains.

Second step is to redirect the new subdomain to the correct directory. You do that on the protected void Application_BeginRequest(Object sender, EventArgs e) on Global.asax using rewritepath

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.Request.Url.Host.StartsWith("subdomain."))
    {
        // here you need to find where to redirect him by reading the url
        // and find the correct file.
        HttpContext.Current.RewritePath("/subdomain/" + Request.Path, false);
    }


    // .... rest code   
}

Its not so easy, not so hard... maybe there are some more minor issues like permissions to write to dns. Also you need to know dns, read the manual about.