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.
Routing in ASP.NET MVC By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional). Now let us create one MVC Application and open RouteConfig.
The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. The Default route maps this URL to the following parameters: controller = Home. action = Index.
Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With