Attribute Based Routing in Core API
Attribute Based Routing in Core API
#FullStackFuture
© NIIT-StackRoute
© NIIT-StackRoute 2022-2023
2022-2023
Outcome
© NIIT-StackRoute 2022-2023
Routing Overview
● Routing is responsible for matching incoming HTTP requests and dispatching those
requests to the app's executable endpoints.
● The endpoint matching process can extract values from the request's URL and provide
those values for request processing.
● ASP.NET Core controllers use the Routing middleware to match the URLs of incoming
requests and map them to actions.
© NIIT-StackRoute 2022-2023
Routing Overview
© NIIT-StackRoute 2022-2023
Routing Overview
app.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Details}/{id?}");
© NIIT-StackRoute 2022-2023
Attribute Routing
© NIIT-StackRoute 2022-2023
Overview
© NIIT-StackRoute 2022-2023
Create a web API project
© NIIT-StackRoute 2022-2023
Create a web API project
© NIIT-StackRoute 2022-2023
Create a web API project
© NIIT-StackRoute 2022-2023
Create a web API project
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
// https://localhost:7192/api/WeatherForecast
[HttpGet]
public string GetFirst()
{
return Summaries[0];
}
//https://localhost:7192/api/WeatherForecast/{id}
[HttpGet("{id}")]
public string GetAny(int id)
{
return Summaries[id - 1];
} © NIIT-StackRoute 2022-2023
Run and Test API
© NIIT-StackRoute 2022-2023
Run and Test API
© NIIT-StackRoute 2022-2023
Add another GET endpoint
// https://localhost:7192/api/WeatherForecast
[HttpGet]
public string GetLast()
{
return Summaries[Summaries.Length - 1];
}
© NIIT-StackRoute 2022-2023
Add another GET endpoint
© NIIT-StackRoute 2022-2023
Add another GET endpoint
// https://localhost:7192/api/WeatherForecast/last
[HttpGet(“last”)]
public string GetLast()
{
return Summaries[Summaries.Length - 1];
}
© NIIT-StackRoute 2022-2023
Run and Test API
© NIIT-StackRoute 2022-2023
Just a Minute
Q1. Which attribute is applied by default on controller when we create API?
a) Api
b) Http
c) ApiController
d) Controller
Ans - c
© NIIT-StackRoute 2022-2023
Recall
Recall
© NIIT-StackRoute 2022-2023
Thank You
#FullStackFuture
© NIIT-StackRoute
© NIIT-StackRoute 2022-20232022-2023