How to Handle Domain name in MVC Routing

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

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 });  

回答1:

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.



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