What is Attribute Routing?
Routing is a middleware to match/dispatch incoming HTTP requests to the application’s executable endpoints(such as MVC actions, API methods, etc.). Attribute routing uses Route attribute and Http verb attributes to define the routes. Attribute routing gives you more control over the URIs in your web API.
How to Enable Attribute Routing?
In the Startup.cs file, add app.UseRouting() and app.UseEndpoints(endpoints => endpoints.MapControllers()) . If your application need authentication and authorization, you need to add them in between the app.UserRouting() and app.UseEndpoints().
All the API controllers in ASP.NET Core 3.1 should inherent from BaseController
and apply [ApiController]
attribute.
The [ApiController]
attribute makes attribute routing a requirement, meaning the API methods are inaccessible via conventional routes.
The [ApiController]
attribute also makes model validation errors automatically trigger an HTTP 400 response. Basically, the framework perform following code behind the scene:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Tokens and Parameters in Route Template
Attribute routes support token replacement by enclosing a token in square-brackets ([
, ]
). The tokens [action]
, [area]
, and [controller]
are replaced with the values of the action name, area name, and controller name.
Attribute routes support the same parameter syntax as conventional routes by enclosing a parameter in curly-brackets ({
, }
).
With attribute routing, the controller and action names play no part in which action is matched, unless token replacement is used.
Route Template
It is most commonl to apply the RouteAttribute on Controller class and Http verb attributes (HttpGet, HttpPost, etc.) applied on actions. The final URL match pattern would be:
Controller Routing Template/HttpVerb Routing Template
However, if the route templates applied to an action begin with /
or ~/
, they would not get combined with route templates applied to the controller.
You can also add multiple route to action by adding the same Http Verb with different route template.
How to Find Out Why the API Method is NOT Invoked
There are several situations the API method is not get called:
- If the method has
Authorize
attribute applied but the user is not authenticated or authorized, the framework would return 401 (Unauthorized) error. - If the method has parameters but the model binding from the request failed, the framework would return 400 (Bad Request) error.
- If there is no end point defined to match the request, the framework would return 404 (Not Found) error.
You can find the source code to demonstrate the web API routing in GitHub here.