Mark Erasmus
Mark Erasmus

Reputation: 2385

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

If I create an MVC action or action link, e.g. @Url.Action("Index", "Home")" I get redirected to http://www.example.com, but what I want is to force it to redirect to http://www.example.com/Home/Index or http://www.example.com/Home. Is there a way to explicitly render the full path? My Google searches are coming up empty.

Upvotes: 8

Views: 11215

Answers (2)

DavidG
DavidG

Reputation: 118937

Url.Action() uses the routing to generate the URL. so if you want to change it, you must change that. It currently says the default controller is Home and default action is Index. Change them to anything else and it should then give you a different URL.

For example your route configuration is probably something like this:

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

Change the defaults to anything else or remove them:

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

Note that doing this means your pages will only be accessible by full controller/action paths so you may want to create a landing page and make that the default.

If you absolutely need to know the full URL of an action then you can do it this way. first create an additional route and put it at the bottom of your route config. This will never get used by the system by default:

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

Then in code you can call this (not sure it's available in Razor, but it should be easy to write a helper method):

var fullURL = UrlHelper.GenerateUrl("AbsoluteRoute", "Index", "Home", null, null, null, null, System.Web.Routing.RouteTable.Routes, Request.RequestContext, false);

Upvotes: 6

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

You will probably need to create a specific route for Home/Index that comes before the default route. Then you can have the default route and the Home/Index route point to the same place. However, this will not redirect you to Home/Index if you go to the base route... so you'll have to add url redirect, either at the IIS level (there are settings to do this) or you can just add code to your Index page to look at the url and redirect to the full url.

Alternatively, you could take away the default controller and action values, and then add url redirection to your IIS config to redirect you to the full path if they go to the root.

Upvotes: 1

Related Questions