Himberjack
Himberjack

Reputation: 5792

Changing website according to subdomain

I have a website written in ASP.NET. I would like to add subdomains of states. such as nevada.mysite.com. However, I'd like my whole site to be custom made for that subdomain. That is, I'd like to capture in each page which subdomain context I am and show different things.

I do not want to seperate to different websites. I want them all to reside in the same website in the IIS

what is the best and proper way of handling such issue? where do you suggest to hold and save the global variable of the state?

Thanks!

Upvotes: 0

Views: 210

Answers (2)

The Muffin Man
The Muffin Man

Reputation: 20004

This is a great question. I've done this before except I didn't use sub domains, I used different URL's, but they still used the same code and database. I wanted a way to integrate this a bit more tightly with my LINQ to SQL code without having to type in where clauses on each one. Here's what I did:

public static IEnumerable<T> GetDataByDomain<T>(
        IQueryable<T> src) where T:IDbColumn
    {
        //1 == website1
        //2 == website2
        //3 == both

        string url = HttpContext.Current.Request.Url.Host;
        int i = url == "localhost"
             || url == "website1.com"
             || url == "www.website1.com" ? 1 : 2;

        return src.Where(x => x.domainID == i|| x.domainID == 3);
    }

Basically when querying a table with LINQ to SQL I have my own custom where clause.

Used like so:

using (var db = new MyDataContext())
        {
            var items = Utility.GetDataByDomain(db.GetTable<Item>()).Where(x => x.isVisible);
        }

Finally in each table where I had data that needed to be specified for one web site or both I added a column that took a value of 1,2 or 3(both). Additionally in my LINQ data context I made a partial class and referenced my interface:

public partial class Item : Utility.IDbColumn
{

}

The reason we need the following interface is because the first method takes an unknown type so obviously I can't select a property from an unknown type unless I tell it that any type I pass to it relies on an interface which contains that property.

Interface:

public interface IDbColumn
    {
        int domainID { get; set; }
    }

It's kind of an interesting system, probably could have done it in many different ways. Built it a while ago and it works great.

Upvotes: 1

RickNZ
RickNZ

Reputation: 18654

First, have all of your subdomains point to a single IP address in DNS.

Next, configure IIS to listen for all connections on that IP (don't specify a host name)

Then write an HttpModule (or perhaps use Global.asax) with a handler for the BeginRequest event. Extract the subdomain name from the incoming URL, and store it in HttpContext.Items["state"] (the Items Dictionary is unique per request).

Upvotes: 1

Related Questions