There is a controller which has two actions which I want to overload depending on incoming parameters. There is a problem: When I write such code on a clean project, everything works as intended, when I transfer the code to a working project, glitches with routing occur: Namely, when one action is called, a completely different controller is drawn with its own action. That is, routing collapses. What am I doing wrong? How to solve such problems correctly? There are no runtime errors. I did not change the default routing settings.
public async Task<IActionResult> Index(int? id)
{
return View("~/Views/File_System/Folder_File_System/Index.cshtml",await _context
.ToListAsync());
}
[HttpGet("/{ParentID}")]
public async Task<IActionResult> Index(int Parent, bool Mode)
{
return View("~/Views/File_System/Folder_File_System/Index.cshtml", await _context
.ToListAsync());
}
CodePudding user response:
What are you trying to achieve is impossible because the problem is caused because the request is matching multiple endpoints which means multiple actions are activated.
What you need to do is treat each action as a sign that shouldn't be duplicated twice.
And to solve this conflic just add a name to the action and you are ready to go as seen in the following example:
public async Task<IActionResult> Index(int? id)
{
return View("~/Views/File_System/Folder_File_System/Index.cshtml", await _context
.ToListAsync());
}
[HttpGet("/{ParentID}", Name = "index2")]
public async Task<IActionResult> Index(int Parent, bool Mode)
{
return View("~/Views/File_System/Folder_File_System/Index.cshtml", await _context
.ToListAsync());
}
The Name Property
can be set with any name you like
Microsoft docs for Name Property: Route Name property
CodePudding user response:
From this, we can see
A method used as a controller action cannot be overloaded.
You can use the attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
But, you'll have to use a different action name for the same http method. Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism. HTTP works on the concept's or URL and URL can only have unique name's.