0

I am learning how ASP.NET Core Web API works, and I am a bit confused on how request's are routed within a controller.

I understand that the URI is typically /controllername-"controller"/action. So something like UsersController would be /api/Users/.

However I have seen some variations in code at work, that either don't include a Route attribute, and the attribute doesn't include a placeholder identifier.

For example a method called Get(int id) within a UsersController is said to be users<id> but how does .Net know this?

Furthermore for something that isn't an obvious Get or Put, but an actual method name like GetWidgetInfo(int widgetId). I'm assuming .NET Core is able to just figure out this takes a URI resource parameter appended after the function name? IE: api/users/getwidgetinfo/<id>. What are the rules for this?

(New .NET Core seems to always have placeholder values on the attribute, but I'm still not sure how it handles naming/routes with methods)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
msmith1114
  • 2,717
  • 3
  • 33
  • 84

1 Answers1

1

Can you clarify if your controller is inheriting ControllerBase? I am assuming you are.

For your first question, since adding a "users/..." to every endpoint is the users controller would be redundant, it is common to have a [Route("api/[controller]")] (or variations of it) before your controller class declaration. My understanding is that since your controller class inherits the ControllerBase class, .NET implicitly knows to route all requests to /users to the controller whose name is "users" (unsure about case sensitivity).

For your second question, this MS docs sheet https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-7.0 , and this StackOverflow post may give you some more insight ASP.NET MVC ambiguous action methods.

For exact inner workings, this MS documentation may contain the information you need https://learn.microsoft.com/en-us/dotnet/architecture/porting-existing-aspnet-apps/routing-differences

sourvad
  • 320
  • 1
  • 6