I have a MVC Web Application that runs on www.domain.com
and I need to configure a different URL binding for another domain www.domain2.com
for the same web application.
The new domain www.domain2.com
will have to return a specific Controller Action View like /Category/Cars
:
routes.MapRoute(
name: "www.domain2.com",
url: "www.domain2.com",
defaults: new { controller = "Category", action = "Cars", id = UrlParameter.Optional }
);
How can I achieve this without changing the URL, so the visitor inserts the url www.domain2.com
and receives the view www.domain.com/category/cars
but the url remains www.domain2.com
?
EDIT:
I have tried this approach but it's not working:
routes.MapRoute(
"Catchdomain2",
"{www.domain2.com}",
new { controller = "Category", action = "Cars" }
);
Domains are normally not part of routes, which is why your examples don't work. To make routes that work only on specific domains you have to customize routing.
The simplest solution for this is to create a custom route constraint and use it to control the domains that a specific URL will match.
DomainConstraint
Usage
If you fire this up in a new project in Visual Studio, you will notice it shows an error. This is because
localhost:<port>
is not a configured domain. However, if you navigate to:You will see the home page.
If you use the URL:
it will run the
CategoryController.Cars
action method (if one exists).Note that since the
Default
route covers a wide range of URLs, most of the site will be available to bothwww.domain.com
andwww.domain2.com
. For example, you will be able to reach the About page both at:You can use the
IgnoreRoute
extension method to block URLs that you don't want (and it accepts route constraints, so this solution will work there, too).This solution will work if you largely want to share functionality between domains. If you would rather have 2 domains in one web site, but make them act like separate web sites, it would be easier to manage if you use an Area for each "web site" in your project by using the above route constraint for the Area routes.
The above configuration would make every URL (that is 0, 1, 2, or 3 segments long) for
www.domain2.com
route to a controller in theDomain2
Area.Agreed with the answer above.
If you want more beautiful implementation - try action filters. Sample of action filters usage from there.
Sample of getting the URL inside action filter from there.
Put the things together and have fun :)
in the default action of the application make sure that the url is the one of the second domain, then return the method that needs. something like: