2 controller routes and a named action

Beau Barker 1 Reputation point
2022-12-05T21:51:40.177+00:00

This question is similar, but removing the name is not a solution to my problem.
https://learn.microsoft.com/answers/questions/347031/exception-is-raised-when-2-controller-routes-and-a.html

My controller has two routes defined, one with a controller-wide parameter and one without. The controller is for report subscriptions. If the parameter is present, then all actions are filtered to operate only on the provided report. If the parameter is missing, then all action are filtered to all reports.

The name is needed to construct valid URLs with the URL helper since the Action method doesn't seem capable. Without names, I have to resort to "knowing" how the URL is constructed at runtime which makes maintenance more difficult if something changes in the future.

Is there a way to construct unique names with multiple routes on a controller?

[Route("reports/subscriptions", Name = "all_report_subs")]  
[Route("reports/{reportName}/subscriptions", Name = "specific_report_subs")]  
public class ReportSubscriptionsController : Controller  
{  
  [HttpGet(Name = "_index")]  
  public IActionResult Index(string? reportName)  
  {  
    // do something  
  }  
}  
  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,815 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 75,386 Reputation points Moderator
    2022-12-06T17:07:10.583+00:00

    you should use UrlHelper.RouteUrl to generate the url. it supports using the route name:

    var url = Url.RouteUrl("specific_report_subs", new RouteValueDictionary   
    {   
       { "reportName", "MyReport" }  
    });  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.