ASP.Net
It is straight forward to create a simple API service by creating a class that extends the 'ApiController' class.
The following creates a Product class that is later used to structure the JSON encoding for each object. Products.cs
using System;
namespace Products.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
using Products.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
namespace Products.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
When run, the following is available at the endpoint:
http://localhost/api/products
[{
"Id": 1,
"Name": "Tomato Soup",
"Category": "Groceries",
"Price": 1.0
}, {
"Id": 2,
"Name": "Yo-yo",
"Category": "Toys",
"Price": 3.75
}, {
"Id": 3,
"Name": "Hammer",
"Category": "Hardware",
"Price": 16.99
}]
References
Get Started with ASP.NET Web API 2 (C#)
https://docs.microsoft.com/en-au/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api