如何处理MVC路由域名 [英] How to Handle Domain name in MVC Routing

查看:271
本文介绍了如何处理MVC路由域名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用路由到我的用户重定向到另一个URL,如果他通过IP地址进入我的网站。

或者如果可能的话,请告诉我,如果有可能通过路由处理域名。正如我可以使用路由控制器和行动,但我也处理域名有或没有?

我目前正在使用像下面,但我无法处理域:

  routes.MapRoute(
                控制器,
                控制器/ {}动作/(编号),
                新{控制器=控制器,行动=索引,ID = UrlParameter.Optional});


解决方案

如果你使用的 IIS 7 ,它可能是更好的Web服务器级别来实现这一点。

这样,正确的状态code将在HTTP头返回给浏览器,你的MVC应用程序可以处理自己的路由,而不必担心域名和主机名,在大多数情况下,是网络服务器的工作。

要在IIS上实现这一目标,在IIS控制台中打开你的网站,并选择 URL重写,并按照下列步骤操作:


  1. 创建一个新规则,比赛URL设置为通配符并输入模式为IP地址 xxx.xxx.xxx.xxx *

  2. 添加一个条件下的 {} HTTP_HOST 等于该网站的IP地址。

  3. 将动作类型重定向,然后输入你想重定向到的格局。 http://mysite.com {R:1}在这种情况下将映射IP地址到其域equivilent后一切,所以xxx.xxx.xxx.xxx/mycontent会重定向到mysite.com/mycontent

此方法将确保您的子目录映射和你的网站仍然是搜索引擎友好,与正在产生应有的反应codeS。

下面的截图显示您的规则可能会如何看待在IIS:

另外,在<一个这个问题href=\"http://stackoverflow.com/questions/278668/is-it-possible-to-make-an-asp-net-mvc-route-based-on-a-subdomain\">ASP.NET MVC路由通过子域,如果你需要你的应用程序的范围内做到这一点可能是有用的。

I am trying to use routing to redirect my user to another URL, if he enters my website through the IP address.

Or if possible please tell me if it possible to handle domain name by routing. As I can use routing for Controller and for Action, but can I also handle Domain in there or not?

I am currently using it like following, but I am unable to handle Domain:

routes.MapRoute(
                "Controller",                                        
                "Controller/{action}/{id}",                          
                new { controller = "Controller", action = "Index", id =     UrlParameter.Optional }); 

解决方案

If you're using IIS 7, it may be better to implement this at web server level.

This way, the proper status code will be returned to the browser in the HTTP header and your MVC app can deal with its own routing without having to worry about domains and hostnames which, in most cases, is the web server's job.

To achieve this on IIS, open your website in the IIS console and select URL Rewrite and follow these steps:

  1. Create a new rule and set the match URL to wildcard and enter the pattern as the IP address as xxx.xxx.xxx.xxx*
  2. Add a condition where {HTTP_HOST} is equal to the site's IP address.
  3. Set the "action type" to redirect, and enter the pattern you wish to redirect to. "http://mysite.com{R:1}" in this case would map everything after the IP address to its domain equivilent, so xxx.xxx.xxx.xxx/mycontent would redirect to mysite.com/mycontent

This approach will ensure your subdirectories are mapped and your site remains search engine friendly, with proper response codes being generated.

The screenshot below shows how your rule might look in IIS:

Alternatively, this question on ASP.NET MVC Routing by Subdomain may be useful if you need to do this within the confines of your app.

这篇关于如何处理MVC路由域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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