简体   繁体   中英

Creating a custom route hierarchy ASP.NET MVC 5

My current url routing is:

website.com/start/id
website.com/upload/id

These routes are wizard steps. My controllers are named StartController, UploadController and my View structure is ~Views/Start/Index.cshtml, ~/Views/Upload/Index.cshtml

The client has requested that he wants the url structure to be:

website.com/build/start/id
website.com/build/upload/id

Wishes:

  • I do not want use a " vanity url " because I want to use @Html.ActionLink and @Url.Action to render my urls whenever possible so I can rename controllers and controller methods later and have those "connected" @Html.ActionLink and @Url.Action update.

  • I do want to have all my methods in a single parent BuildContoller that references a nested View folder structure having my controller methods returing the following views: return View("~/Views/Build/Start/Index.cshtml") . I want to be able to have my View physical structure map/match to my controller naming conventions so return View(); works in controller methods.

My Question:

Is there way that I can respect my "Wishes" above and achieve this custom Url Structure without having to create a BuildController that contains both my StartController methods and my UploadController methods?

I have no problem creating a BuildController or changing the physical structure of my View folders and or controllers but I want to respect the ability of @Url.Action("Start", "Build") and not have to write "manually" in my code " build/start " and, more importantly, keep my StartController and UploadController code because I do not want a long massive bunch of code in my BuildController.

I would switch to attribute routining. You will have to change your ActionLink methods to RouteLink methods but it will work the same way.

Add the attribute

[Route("build/start/{id:int}", Name = "WizardStep1")]

for each controller method (changing the route appropriately).

To generate a link, use RouteLink:

@Html.RouteLink("WizardStep1", ...)

Replacing the ... with the additional code you need to set the URL attributes.

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