I've got 3 domain names all pointed at the same MVC2 application. What I've got now is the homecontroller acting as a traffic cop and redirecting to controllers and views for the specific host name. But I don't like the URI result this causes...
ex: www.webhost1.com/webhost1/imagegallery www.webhost2.com/webhost2/imagegallery
I'd prefer to have:
www.webhost1.com/imagegallery
Is there a way to define the routes in global.asax that would include the host name in the routing evaluation so that the URI looks less redundant?
Aha!, it took a bit of fiddling (and a peak in and old book) but I think I've solved it.
You need to create a custom route constraint. This is the one I made quickly:
public class hostnameConstraint : IRouteConstraint
{
protected string _hostname;
public hostnameConstraint (string hostname)
{
_hostname = hostname;
}
bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext.Request.Url.Host == _hostname)
return true;
return false;
}
}
Then you simply add it to your routes and specify which hostname you want the route to apply to. like so:
routes.MapRoute(
"ImageGallery", "{controller}/{action}",
new { controller = "Home", action = "Index"},
new { hostname = new hostnameConstraint("webhost1.com") }
);
routes.MapRoute(
"ImageGallery", "{controller}/{action}",
new { controller = "Home", action = "Index"},
new { hostname = new hostnameConstraint("webhost2.com") }
);
and so on and so forth. I don't know how your routes are layed out, but the point is that now you can have seperate routes for the hostnames. Which should enable you to do what you're after.
来源:https://stackoverflow.com/questions/4216098/how-can-host-name-be-included-in-mvc2-route-mapping