ASP.NET Web API Routing in ApiController

I struggled with my routing for some time, and after a few days, trying to find a Google solution without any luck, I hope someone can illuminate my problem.

My WebApiConfig has the following routes:

config.Routes.MapHttpRoute( name: "AccountStuffId", routeTemplate: "api/Account/{action}/{Id}", defaults: new { controller = "Account", Id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "AccountStuffAlias", routeTemplate: "api/Account/{action}/{Alias}", defaults: new { controller = "Account", Alias = RouteParameter.Optional } ); 

and the following controller methods:

  [HttpGet] public Account GetAccountById(string Id) { return null; } [HttpGet] public Account GetAccountByAlias(string alias) { return null; } 

If I call: /API/Account/GetAccountById/stuff , then it correctly calls GetAccountById .

But if I call /API/Account/GetAccountByAlias/stuff , then nothing will happen.

It’s clear that order is taking place here, because if I switch my route advertisements in my WebApiConfig, then /API/Account/GetAccountByAlias/stuff correctly calls GetAccountByAlias , and /API/Account/GetAccountById/stuff does nothing.

The two [HttpGet] decorations are part of what I found on Google, but they don't seem to solve the problem.

Any thoughts? Am I doing something obviously wrong?

Edit:

When a route fails, the page displays the following:

 <Error> <Message> No HTTP resource was found that matches the request URI 'http://localhost:6221/API/Account/GetAccountByAlias/stuff'. </Message> <MessageDetail> No action was found on the controller 'Account' that matches the request. </MessageDetail> </Error> 
+4
source share
2 answers

You should only have the following route:

 config.Routes.MapHttpRoute( name: "AccountStuffId", routeTemplate: "api/Account/{action}/{Id}", defaults: new { controller = "Account", Id = RouteParameter.Optional } ); 

and follow these steps:

 [HttpGet] public Account GetAccountById(string Id) { return null; } [HttpGet] public Account GetAccountByAlias([FromUri(Name="id")]string alias) { return null; } 
+6
source

Is there a reason why you need to declare two different routes?

Take a look at the manual at: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

They have one default route, and with the example that you need in your configuration,

 routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); 
+1
source

Source: https://habr.com/ru/post/1495013/


All Articles