Asp.Net Routing - Display complete URL

妖精的绣舞 提交于 2019-11-26 18:34:28

问题


I have a domain "http://www.abc.com". I have deployed an ASP.net MVC4 app on this domain. I have also configured a default route in RouteConfig.cs as shown below

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"

Everything works as expected but the address bar in the browser shows "http://www.abc.com" instead of "http://www.abc.com/MyApp/Home". Is there any way to force the browser to show the complete URL including the controller and Action?


回答1:


One option would be to set your default route to a new controller, maybe called BaseController with an action Root:

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

and modify your RouteConfig to point to that for root requests:

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



回答2:


You'll need to do some kind of url rewriting. Probably the quickest way is to add a RewritePath call to your BeginRequest in Global.asax. 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. Or you could use Microsoft URL Rewrite, but that's more complicated IMO.




回答3:


Just remove the default parameters, it's been answered here:

How to force MVC to route to Home/Index instead of root?



来源:https://stackoverflow.com/questions/13131929/asp-net-routing-display-complete-url

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