Reputation: 4492
Is it possible to have one .NET MVC application, and have it accessible from different domains, in such a way that the content will be domain-dependant?
For example, both www(dot)site1(dot)com and www(dot)site2(dot)com will point to my server's IP, and to the same website in IIS. In that website my .NET MVC application will reside. Now, I want the ability to know which site (domain name) triggered the ControllerAction, and act accordingly (for example, display different content for the homepage in the Index action, or allow/prevent access to specific content assigned to a specific site).
I would appreciate any help on this. I can accept an extra parameter passed to all controller actions (probably using Routing), but if there's a more elegant solution that would be ideal.
Upvotes: 2
Views: 3590
Reputation:
I have written a blog post about how to do this with an example web application for download.
It uses an abstract base Controller that is aware of the site it is being called for - by creating controllers that inherit from this base class you have automatic access to the current "site" for the current request.
It also allows you to load all your sites from a single database - can save you a bit on hosting fees if you're on a shared host, or if you run your own server you don't have to set up a new database for each site you create.
Upvotes: 1
Reputation: 4660
If you use different databases to keep the data separate, then in the Session Start configure the application to use one of the databases based on the Server Name variable. Then place the working connection string in the session for the user.
protected void Session_Start(Object sender, EventArgs e)
{
NameValueCollection NVCSrvElements = Request.ServerVariables;
switch (NVCSrvElements.Get("SERVER_NAME"))
{
case "www.whatever1.com":
Session["ConnStr"]="db1 connection string";
break;
case "www.whatever2.com":
Session["ConnStr"] = "db2 connection string";
break;
}
}
Then use this connection string in the rest of the application.
Upvotes: 0
Reputation: 6143
You can easily access the domain name used in the request with something along the lines of the following:
switch(Request.ServerVariables("SERVER_NAME"))
{
case "www.site1.com":
//do something
case "www.site2.com":
//do something else
default:
//????
}
You can do this in anywhere you have access to the Request object.
Upvotes: 1
Reputation: 60498
Well, you can always get the domain from the Request.RawUrl property.
As Mercer mentioned, deploying these as two separate web apps would be a better solution though. If that isn't possible, I would try to design something relatively generic that would check the domain and return different Views for each domain.
Upvotes: 2
Reputation: 4678
An elegant solution would be to have 2 deployments for 2 domains, and to separate content.
You could still have common content, but separating the content without hardcoding this inside the application is a win situation.
Upvotes: 0