This simple tutorial will guide you through the steps to create a simple Web API using C# and .NET Core and then test it using Postman.
First, open Visual Studio and create a new ASP.NET Core Web API project.
In the solution explorer, right-click the Controllers
folder and add a new controller.
Controllers
folder, select Add, then New Item.ProductsController
, then click Add.Replace the content of ProductsController.cs
with the following code:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace YourNamespace.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private static readonly List Products = new List
{
"Product1",
"Product2",
"Product3"
};
[HttpGet]
public ActionResult> Get()
{
return Products;
}
[HttpGet("{id}")]
public ActionResult Get(int id)
{
if (id < 0 || id >= Products.Count)
{
return NotFound();
}
return Products[id];
}
[HttpPost]
public void Post([FromBody] string value)
{
Products.Add(value);
}
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
if (id >= 0 && id < Products.Count)
{
Products[id] = value;
}
}
[HttpDelete("{id}")]
public void Delete(int id)
{
if (id >= 0 && id < Products.Count)
{
Products.RemoveAt(id);
}
}
}
}
Now, run the API by pressing F5 or clicking the Run button in Visual Studio. The API will start, and you should see a browser window open with the URL https://localhost:{port}/api/products
.
You can test the API endpoints using a web browser or Postman.
Postman is a powerful tool for testing APIs. Follow these steps to test your API:
https://localhost:{port}/api/products
. Click Send to get the list of products.https://localhost:{port}/api/products/{id}
to get a product by ID.https://localhost:{port}/api/products
with a JSON body to add a new product (e.g., {"value":"Product4"}
).https://localhost:{port}/api/products/{id}
with a JSON body to update a product (e.g., {"value":"UpdatedProduct"}
).https://localhost:{port}/api/products/{id}
to delete a product by ID.Note: Replace {port}
with the actual port number your application is running on, which you can find in the browser address bar or in the application properties in Visual Studio.
In this tutorial, you learned how to create a simple Web API using C# and .NET Core and how to test it using Postman. This is just a starting point; you can extend the API with more complex logic, authentication, and other features as needed.