How can host name be included in MVC2 route mapping?

喜夏-厌秋 提交于 2019-12-08 07:54:41

问题


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?


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!