Search code examples
c#asp.net-mvc.net-coreasp.net-core-mvcasp.net-mvc-routing

How can I add an alternative route to a controller method in MVC Core to support a legacy endpoint


The following code I am trying is changing the route so that it is only accessible via [Area]/[Controller]/DailyStatusSummary - is there any way to just add it as an alternative route?

    [HttpGet("[Area]/[Controller]/DailyStatusSummary")]

    public async Task<IActionResult> CompanyStatusSummary()
    { 
        ... etc.

Background: I used to have a controller action named DailyStatusSummary. I have refactored my code to give better names to actions, and this means this action in particular is now called CompanyStatusSummary. I am wary some users have bookmarks to the old DailyStatusSummary endpoint as it's a popular page, so I am trying to add this as an alternative route (so if you navigate to either the old or new endpoint, it hits the CompanyStatusSummary action.)


Solution

  • In App_Start\RouteConfig.cs you can create a specific route. Assuming your area is "areaABC" and your controller is "controllerXYZ", and only the action changes, something like this may work:

    routes.MapRoute(
        name: "Alternate",
        url: "areaABC/controllerXYZ/DailyStatusSummary",
        defaults: new { area = "areaABC", controller = "controllerXYZ", action = "CompanyStatusSummary"}
    );
    

    And the action in the controller should keep the CompanyStatusSummary (or remove if catched with generic route):

    [HttpGet("[Area]/[Controller]/CompanyStatusSummary")]
    
    public async Task<IActionResult> CompanyStatusSummary()
    { 
    

    For .Net Core 3.1, the route mapping should be done in app.UseEndpoints, mapping the controller route:

    endpoints.MapControllerRoute(
        name: "Alternate",
        pattern: "areaABC/controllerXYZ/DailyStatusSummary",
        defaults: new { area = "areaABC", controller = "controllerXYZ", action = "CompanyStatusSummary" });