Introduction
In this tutorial, we’ll walk through creating a simple RESTful API using ASP.NET MVC in C#. This API will return student information (such as student ID, name, date of birth, zip code, and major department) when queried with a specific student ID.
This guide is tailored for beginners and includes explanations, code walkthroughs, and practical steps to help you understand and implement the project.
Tools Required
- Visual Studio 2019/2022 (Community Edition is free)
- .NET Framework (4.7 or later)
- Basic knowledge of C# syntax
Step 1. Create a New Web API Project
- Open Visual Studio.
- Click on File > New > Project.
- Choose ASP.NET Web Application (.NET Framework).
- Name your project StudentAPI and click OK.
- Select the Web API template and click Create.
This sets up a basic project with preconfigured folders for Models, Controllers, and API routes.
Step 2. Create the Student Model
This model defines the structure of the student data.
File: Models/Student.cs
using System;
namespace StudentAPI.Models
{
public class Student
{
public string StudentId { get; set; } // Alphanumeric ID e.g. S1001
public string Name { get; set; } // Full name e.g. Aravind Raj
public DateTime DateOfBirth { get; set; } // e.g. 2001-06-15
public string ZipCode { get; set; } // e.g. 600001
public string Major { get; set; } // e.g. Computer Science
}
}
Explanation
- StudentId: Alphanumeric identifier for the student.
- Name: Full name of the student.
- DateOfBirth: The date of birth, stored as a DateTime object.
- ZipCode: Postal code of the student’s residence.
- Major: The department or field of study.
Step 3. Create the API Controller
The controller processes incoming HTTP requests and returns responses.
File: Controllers/StudentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using StudentAPI.Models;
namespace StudentAPI.Controllers
{
public class StudentController : ApiController
{
private static List<Student> students = new List<Student>
{
new Student
{
StudentId = "S1001",
Name = "Karthik Varma",
DateOfBirth = new DateTime(2000, 3, 12),
ZipCode = "600045",
Major = "Mechanical Engineering"
},
new Student
{
StudentId = "S1002",
Name = "Meenakshi R",
DateOfBirth = new DateTime(2001, 7, 25),
ZipCode = "641001",
Major = "Electronics and Communication"
},
new Student
{
StudentId = "S1003",
Name = "Sundar Rajan",
DateOfBirth = new DateTime(1999, 12, 30),
ZipCode = "500081",
Major = "Computer Science"
}
};
// GET api/student/{id}
public IHttpActionResult GetStudentById(string id)
{
var student = students.FirstOrDefault(
s => s.StudentId.Equals(id, StringComparison.OrdinalIgnoreCase));
if (student == null)
{
return NotFound();
}
return Ok(student);
}
}
}
Explanation
- We use an in-memory List<Student> to simulate a database.
- The method GetStudentById accepts an ID as input.
- It searches for the student in the list using LINQ.
- If found, it returns the student data in JSON format.
- If not found, it returns a 404 (Not Found) HTTP response.
Step 4. Configure Web API Routing
Ensure your app correctly maps incoming API requests.
File: App_Start/WebApiConfig.cs
using System.Web.Http;
namespace StudentAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Define default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Explanation
- Enables attribute routing.
- Sets a default route pattern: api/{controller}/{id}.
- This means a call to api/student/S1001 will map to StudentController.
Step 5. Run and Test Your API
- Press F5 or click Start Debugging in Visual Studio.
- The browser will open. Change the URL to:
http://localhost:1234/api/student/S1002
(Replace the port 1234 with your actual port number.)
Example Output
{
"StudentId": "S1002",
"Name": "Meenakshi R",
"DateOfBirth": "2001-07-25T00:00:00",
"ZipCode": "641001",
"Major": "Electronics and Communication"
}
Summary
In this tutorial, you’ve learned.
- How to set up an ASP.NET Web API project.
- How to create a model and controller.
- How to simulate a student database using a list.
- How to return JSON responses using RESTful routes.
Next Steps for Learning
- Replace the static list with a database (SQL Server + Entity Framework).
- Add endpoints for POST (create), PUT (update), and DELETE (remove).
- Add input validation and error handling.
Hands-On Practice
- Try adding a new student to the list.
- Customize the model by adding more fields, such as phone number and email.
- Add unit tests using NUnit or xUnit.
I encourage you to experiment with different student profiles and build upon this basic API to enhance your understanding.
Happy Learning!