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

If I create a link to an MVC action or action, for example. @Url.Action("Index", "Home")" I am redirecting to http://www.example.com , but I want to force it to redirect to http://www.example.com/Home/Index or http: //www.example.com/Home . Is there a way to explicitly make the full path? My Google searches look empty.

+4
source share
2 answers

Url.Action() uses routing to create the URL. therefore, if you want to change it, you must change it. He currently says that the default controller is Home , and the default action is Index . Change them to something else and then it will 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 default values ​​to something else or delete them:

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

Please note that this means that your pages will only be accessible through the full controller/action paths, so you might want to create a landing page and do this by default.

If you absolutely need to know the full action URL, you can do it this way. first create an additional route and place it at the bottom of the route configuration. This will never be used by the system by default:

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

Then in the code you can call this (not sure if it is 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); 
+4
source

You will probably need to create a specific route for the Home / Index that precedes the default route. Then you can specify the default route and the Home / Index route point to the same place. However, this does not redirect you to the main / index if you go to the base route ... so you have to add URL redirection either at the IIS level (there are settings for this), or you can just add the code to your index page to view the URL and redirect to the full URL.

Alternatively, you can override the controller and the default action values, and then add the URL redirection to the IIS configuration to redirect you to the full path if they go to the root directory.

+1
source

Source: https://habr.com/ru/post/1442892/


All Articles