How can host name be included in MVC2 route mapping?

守給你的承諾、 提交于 2019-12-08 01:29:27

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.

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