Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core 2 multiple Controllers

Tags:

asp.net-core

I created a ASP.Net Core 2.0 with One controller, no problem. Then I added another Controller, then this Exception appears:

InvalidOperationException: The following errors occurred with attribute routing information:

Error 1: Attribute routes with the same name 'Get' must have the same template: Action: 'Patrimonio.Controllers.CategoriaController.Getcc (Patrimonio)' - Template: 'api/Categoria/{id}' Action: 'Patrimonio.Controllers.PatrimonioController.Getac (Patrimonio)' - Template: 'api/Patrimonio/{id}' Microsoft.AspNetCore.Mvc.Internal.ControllerActionDescriptorBuilder.Build(ApplicationModel application)

the first Controller has

 // GET: api/Categoria
 [Route("api/Categoria")]
 public class CategoriaController : Controller
 ...
 [HttpGet]
 public IEnumerable<string> Geta()
 {
     return new string[] { "value1", "value2" };
 }

the second has

 // GET: api/Patrimonio/5
 [Route("api/Patrimonio")]
 public class PatrimonioController : Controller
 ...
 [HttpGet("{id}", Name = "Get")]
 public string Getac(string id)
 {
     return "value" + id;
 }

Even with the Getac and Getcc, ASP.Net Core complains about same name 'Get' .

How to solve this?

like image 652
Tony Avatar asked Oct 03 '17 20:10

Tony


1 Answers

Your error message does not correspond to the code you posted. But it appears that you have two [Http*(Name = "Get")] annotations in your program. Route names, however, must be unique.

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#route-name

Or more precisely, it appears from the error message that two actions with the same route name must have exactly the same URL template. The reason for this is that the route name is primarily used for reverse routing (i.e. generating a URL to an action), and if the name isn't unique then the URL is ambiguous - unless all routes with that name have the same template.

Try replacing

[HttpGet("{id}", Name = "Get")]

with

[HttpGet("{id}")]
like image 156
Sebastian Redl Avatar answered Sep 19 '22 23:09

Sebastian Redl