I continue the epic with routing

Controller methods:

public Object Get(int id) { PrivateConsultant cons = consMng.GetById(id); PrivateConsultantVM result = new PrivateConsultantVM { Name = cons.Name, Surname = cons.Surname, Patronymic = cons.Patronymic, Rating = cons.Rating, ServicesTitles = serviceMng.GetTitles(cons.Id) }; return Ok(new { result, date = DateTime.Now }); } [HttpGet] public Object GgetByEntityId(int id) { return Ok(new { result = "GetByEntityId" }); } 

(2 g introduced specially)

Setting up the routing:

  config.Routes.MapHttpRoute( name: "ActionRoute", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { }, constraints: new { action = new AlphaRouteConstraint(), } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { }, constraints: new { id = new IntRouteConstraint() } ); 

Only this method works:

 http://localhost:54788/api/consultants/GgetByEntityId/1 

If so

 http://localhost:54788/api/consultants/1 

that mistake

 <Error> <Message>Произошла ошибка.</Message> <ExceptionMessage> Найдено несколько действий, соответствующих запросу: Get на типе WebApplication1.Controllers.ConsultantsController GgetByEntityId на типе WebApplication1.Controllers.ConsultantsController </ExceptionMessage> <ExceptionType>System.InvalidOperationException</ExceptionType> <StackTrace> в System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext) в System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext) в System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) в System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext() </StackTrace> </Error> 

I do not understand why, it should work. When the 2nd request is in progress, the routing matches it with the ActionRoute route. The unit in the request is mapped to {action}, but since the action has a string limit, then the request is compared with the DefaultApi route.

Where is the mistake?

  • one
    You have 2 methods in your controller. One is called Get , the second is marked with the [HttpGet] attribute with a default route. How does asp.net understand what to call? - tym32167
  • @ tym32167 why does it work in the first case? (I ask for curiosity). - Monomax
  • one
    because in the first you explicitly said what action to call api/consultants/GgetByEntityId/1 - tym32167
  • one
    According to REST, you should not have a GgetByEntityId method - tym32167
  • one
    методы типа GetByCategoryId I would do api/category/{mycategory}/product - for the list of products by category - tym32167

0