• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Wednesday, July 1, 2020

Route Prefix in Web API

 Admin     July 01, 2020     .Net, Asp.Net, C#, Web API     No comments   

In this article, I am going to discuss the Attribute Routing Route Prefix in Web API with some examples. We are going to work with the same example that we started in Web API Attribute Routing article and continue in Optional Parameters in Web API Attribute Routing article of this Web API article series. At the end of this article, you will understand What is Route Prefix in Web API and when and how to use Web API Route Prefix with an example.

ASP.NET Web API Attribute Routing Route Prefix
Let’s understand the use of Web API Attribute Routing Route Prefix with one example. Let’s modify the StudentController class as shown below.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace AttributeRoutingInWEBAPI.Controllers
{
    public class StudentsController : ApiController
    {
        static List<Student> students = new List<Student>()
        {
            new Student() { Id = 1, Name = "Pranaya" },
            new Student() { Id = 2, Name = "Priyanka" },
            new Student() { Id = 3, Name = "Anurag" },
            new Student() { Id = 4, Name = "Sambit" }
        };
        [HttpGet]
        [Route("students")]
        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }
        [HttpGet]
        [Route("students/{studentID}")]
        public Student GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }
        [HttpGet]
        [Route("students/{studentID}/courses")]
        public IEnumerable<string> GetStudentCourses(int studentID)
        {
            List<string> CourseList = new List<string>();
            if (studentID == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (studentID == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (studentID == 3)
                CourseList = new List<string>() { "ASP.NET WEB API", "C#.NET", "Entity Framework" };
            else
                CourseList = new List<string>() { "Bootstrap", "jQuery", "AngularJs" };
            return CourseList;
        }
    }
}

As you can see from the above example, we are using the route attributes at the action level to define the routes, and furthermore, all the routes in the StudentsController start with the same prefix – students that mean students is the common prefix for all the routes available in the Student Controller.

Here, you can set the common prefix “students” for the entire Student Controller by using the [RoutePrefix] attribute as shown below at the controller level.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace AttributeRoutingInWEBAPI.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : ApiController
    {
        static List<Student> students = new List<Student>()
        {
            new Student() { Id = 1, Name = "Pranaya" },
            new Student() { Id = 2, Name = "Priyanka" },
            new Student() { Id = 3, Name = "Anurag" },
            new Student() { Id = 4, Name = "Sambit" }
        };
        [HttpGet]
        [Route]
        //This will be translated to /students 
        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }
        [HttpGet]
        [Route("{studentID}")]
        //This will be translated to /students/2
        public Student GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }
        [HttpGet]
        [Route("{studentID}/courses")]
        //This will be translated to /students/2/course
        public IEnumerable<string> GetStudentCourses(int studentID)
        {
            List<string> CourseList = new List<string>();
            if (studentID == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (studentID == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (studentID == 3)
                CourseList = new List<string>() { "ASP.NET WEB API", "C#.NET", "Entity Framework" };
            else
                CourseList = new List<string>() { "Bootstrap", "jQuery", "AngularJs" };
            return CourseList;
        }
    }
}

The Route Prefix attribute eliminates the need to repeat the common prefix “students” on each and every controller action method. However, sometimes we may need to override the route prefix attribute. Let us understand this with an example

First, add a class file with the name “Teacher.cs” within the Models Folder. To do so right-click on the model’s folder, and then add a new class file with the name “Teacher.cs”. Then Copy and paste the following code in it.
namespace AttributeRoutingInWEBAPI.Models
{
    public class Teacher
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Add the below GetTeachers() action method within the “StudentsController”.
Web API Attribute Routing Route Prefix

After adding the GetTeachers() action in the “StudentsController” class, we want GetTeachers() action to be mapped to the URI “tech/teachers“.
ASP.NET Web API Attribute Routing Route Prefix

If we use the [Route] attribute on GetTeachers() method as shown in the above image and when we navigate to tech/teachers, we get the following error.
Route Prefix in Attribute Routing

But if we navigate to /students/tech/teachers then we get the output as expected that the list of teachers. This is because the [RoutePrefix(“students”)] attribute on StudentsController. Now the question that comes to our mind is how to override the RoutePrefix attribute used in the StudentsController. To override the RoutePrefix we need to use the ~ (tilde) symbol as shown below.
Removing Route Prefix in Attribute Routing

With the above change, now the GetTeachers() action method is mapped to URI “/tech/teachers” as expected.

What is the use of the RoutePrefix attribute?
The RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate the need to repeat the common route prefix on each and every controller action.

How to override the route prefix?
Use ~ character to override the route prefix

In the next article, I am going to discuss Web API Route Constraint in Attribute Routing. Here, In this article, I try to explain the Web API Route Prefix with some examples. I hope you enjoy this article.

Summary:
I Hope this post will be helpful to understand the concept of Route Prefix in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape