Asp.Net Routing – 显示完整的URL

我有一个域名“http://www.abc.com”。 我在这个域上部署了一个ASP.net MVC4应用程序。 我还在RouteConfig.cs中配置了默认路由,如下所示

routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "MyApp", action = "Home", id = UrlParameter.Optional } ); 

以上映射确保任何试图访问“http://www.abc.com”的人自动显示“http://www.abc.com/MyApp/Home”页面

一切都按预期工作,但浏览器中的地址栏显示“http://www.abc.com”而不是“http://www.abc.com/MyApp/Home”。 有没有办法强制浏览器显示完整的URL,包括控制器和动作?

一种选择是将您的默认路由设置为新控制器,可能称为具有操作Root BaseController

 public class BaseController : Controller { public ActionResult Root() { return RedirectToAction("Home","MyApp"); } } 

并修改您的RouteConfig以指向root请求:

 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Base", action = "Root", id = UrlParameter.Optional } ); 

你需要做一些url重写。 可能最快的方法是在Global.asax中向BeginRequest添加RewritePath调用。 在你的情况下,它是这样的:

 void Application_BeginRequest(Object sender, EventArgs e) { string originalPath = HttpContext.Current.Request.Path.ToLower(); if (originalPath == "/") //Or whatever is equal to the blank path Context.RewritePath("/MyApp/Home"); } 

一种改进是动态地从路由表中提取url以进行替换。 或者您可以使用Microsoft URL Rewrite ,但这更复杂的IMO。

只需删除默认参数,这里已经回答:

如何强制MVC路由到Home / Index而不是root?