Asp.Net Routing – Display complete URL

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

Method 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.

Method 3

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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x