Web API attribute routing constraints

Video ready, click here to close ×


Text version of the video
http://csharp-video-tutorials.blogspot.com/2017/02/web-api-attribute-routing-constraints.html

Slides
http://csharp-video-tutorials.blogspot.com/2017/02/web-api-attribute-routing-constraints_20.html

All ASP .NET Web API Text Articles and Slides
http://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-tutorial-for-beginners.html

All ASP .NET Web API Videos

Video ready, click here to close ×

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

All Dot Net and SQL Server Tutorials in Arabic
https://www.youtube.com/c/KudvenkatArabic/playlists

In this video we will discuss Attribute Routing Constraints in ASP.NET Web API. Let’s understand these constraints with an example.

Consider the following StudentsController.

[RoutePrefix(“api/students”)]
public class StudentsController : ApiController
{
static List[Student] students = new List[Student]()
{
new Student() { Id = 1, Name = “Tom” },
new Student() { Id = 2, Name = “Sam” },
new Student() { Id = 3, Name = “John” }
};

[Route(“{id}”)]
public Student Get(int id)
{
return students.FirstOrDefault(s =] s.Id == id);
}
}

If we navigate to /api/students/1, Get(int id) action method is mapped to the URI and we get the details of the student whose id is 1 as expected.

In addition to retrieving student by Id, we also want to retrieve student by “name”. So let’s add another Get() method as shown below. Notice the name of the parameter is name and it’s type is string.

[RoutePrefix(“api/students”)]
public class StudentsController : ApiController
{
static List[Student] students = new List[Student]()
{
new Student() { Id = 1, Name = “Tom” },
new Student() { Id = 2, Name = “Sam” },
new Student() { Id = 3, Name = “John” }
};

[Route(“{id}”)]
public Student Get(int id)
{
return…

source

7 comments

Leave a Reply

Your email address will not be published. Required fields are marked *