如何主机名被包括在MVC2路由映射? [英] How can host name be included in MVC2 route mapping?

查看:104
本文介绍了如何主机名被包括在MVC2路由映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3域名都在同一MVC2应用程序指出。我现在所得到的是作为一个交通警察,并重定向到控制器和视图为特定的主机名HomeController的。但我不喜欢的URI结果这导致...

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...

例如:
www.webhost1.com/webhost1/imagegallery
www.webhost2.com/webhost2/imagegallery

ex: www.webhost1.com/webhost1/imagegallery www.webhost2.com/webhost2/imagegallery

我preFER有:

www.webhost1.com/imagegallery

www.webhost1.com/imagegallery

有没有办法在Global.asax中定义的路线将包括路由评测主机名称,以便URI看起来少冗余?

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.

这篇关于如何主机名被包括在MVC2路由映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆