Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...