Creating a Simple Test Web API in C#
Introduction
In this blog post, we will create a simple Web API using C# and ASP.NET Core that supports basic CRUD operations such as GET, POST, and DELETE. This API will return test data, making it ideal for learning and testing API development.
Prerequisites
Step 1: Create a New ASP.NET Core Web API Project
Open a terminal or command prompt and run the following command:
dotnet new webapi -n TestApi
Navigate to the project directory:
cd TestApi
Step 2: Create a Test Model
In the Models folder, create a new class named TestData.cs:
领英推荐
namespace TestApi.Models
{
public class TestData
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Step 3: Create a Controller
In the Controllers folder, create a new controller named TestController.cs:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace TestApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private static List<TestData> _testData = new List<TestData>
{
new TestData { Id = 1, Name = "Item 1" },
new TestData { Id = 2, Name = "Item 2" }
};
[HttpGet]
public IActionResult Get()
{
return Ok(_testData);
}
[HttpPost]
public IActionResult Post([FromBody] TestData data)
{
_testData.Add(data);
return CreatedAtAction(nameof(Get), new { id = data.Id }, data);
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var item = _testData.Find(x => x.Id == id);
if (item == null) return NotFound();
_testData.Remove(item);
return NoContent();
}
}
}
Step 4: Run the API
Run the following command to start the API:
dotnet run
The API will be available at https://localhost:5001/api/test.
Step 5: Test the API
Use Postman or any API testing tool to test the endpoints:
Conclusion
This simple Web API in C# demonstrates basic CRUD operations with test data. You can extend it further to connect with a database or add authentication as needed. Happy coding!
Contact us on WhatsApp for More details: +91 9821150988