简体   繁体   中英

Hardcode URL in ASP.Net MVC 2 route

This is the default route that is given when you create a project -

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

But, here, only when you type http://example.com/Home/About the about page will be shown.

I want to show the about page when the user types http://example.com/About

How can I do it without writing a controller called About?

This is not working:

routes.MapRoute("About", "About", new { controller = "Home", action = "About", id = UrlParameter.Optional });

How can I modify it so that when /About is requested, about page is shown?

Try adding this Before your other route:

routes.MapRoute(
            "Home", // Route name
            "{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

Keep in mind that "{controller}/{action}/{id}" will try to match the non-domain portion of your url. Therefore you need to try and match the url you want with a route.

You have the following url:

www.mydomain.com/About

Where you know the controller must be "Home" and the action must be "About". Therefore, you can match your route using something like this:

www.mydomain.com/{action}

However, the domain portion will need to be removed, so you end up with

{action}

You will then need to set the default route values as seen in the example above. Now, if we go to the domain, we will get routed to the "Home" controller and the "About" action. If we go to www.mydomain.com/HelloWorld, we would get routed to the "Home" controller and the "HelloWorld" action. we can add an optional "id" parameter like so:

{action}/{id}

But we'll need to make sure that the default id is set to UrlParameter.Optional

Hope this helps: :)

edit:

If you want to HARD CODE a url to a specifc route, you can set the default route parameters to the route you need, and then just use the non-domain portion of the url as the route capture.

so, instead of "{controller}/{action}/{id}", you would use "OldSite/MyOldPage.aspx"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM