简体   繁体   English

Asp.Net路由-显示完整的URL

[英]Asp.Net Routing - Display complete URL

I have a domain "http://www.abc.com". 我有一个域“ http://www.abc.com”。 I have deployed an ASP.net MVC4 app on this domain. 我已经在此域上部署了ASP.net MVC4应用程序。 I have also configured a default route in RouteConfig.cs as shown below 我还在RouteConfig.cs中配置了默认路由,如下所示

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

The above mapping ensures that anyone attempting to visit "http://www.abc.com" is automatically shown the page for "http://www.abc.com/MyApp/Home" 上面的映射确保了任何尝试访问“ http://www.abc.com”的人都会自动显示“ http://www.abc.com/MyApp/Home”页面

Everything works as expected but the address bar in the browser shows "http://www.abc.com" instead of "http://www.abc.com/MyApp/Home". 一切正常,但浏览器中的地址栏显示“ http://www.abc.com”,而不是“ http://www.abc.com/MyApp/Home”。 Is there any way to force the browser to show the complete URL including the controller and Action? 有什么方法可以强制浏览器显示完整的URL,包括控制器和Action?

You'll need to do some kind of url rewriting. 您需要进行某种形式的url重写。 Probably the quickest way is to add a RewritePath call to your BeginRequest in Global.asax. 最快的方法可能是将RewritePath调用添加到Global.asax中的BeginRequest中。 In your case it'd be something like this: 在您的情况下,可能是这样的:

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

An improvement would be to dynamically pull the url from the route table for the replacement. 一种改进是从路由表中动态提取URL以进行替换。 Or you could use Microsoft URL Rewrite , but that's more complicated IMO. 或者,您可以使用Microsoft URL Rewrite ,但这是更复杂的IMO。

One option would be to set your default route to a new controller, maybe called BaseController with an action Root : 一种选择是将您的默认路由设置为一个新的控制器(可能称为BaseController并带有一个Root动作:

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

and modify your RouteConfig to point to that for root requests: 并修改RouteConfig使其指向根请求:

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

Just remove the default parameters, it's been answered here: 只需删除默认参数,即可在此处得到解答:

How to force MVC to route to Home/Index instead of root? 如何强制MVC路由到Home / Index而不是root?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM