You can create Custom APIs using the standard WebApi Controllers. But it's recommended that you add a base class for all your APIs to enable code reuse for common things such as security.
In your Website project, Add a folder named API and add the following class:
using MSharp.Framework.Api;
namespace Controllers.API
{
public class BaseApiController : ApiController
{
protected new User User => base.User as User;
}
}
You can come back to this and add more code that you want to reuse in other application controllers later on.
Each API class should be for dealing with one particular aspect of the system (e.g. Authentication, or Product management, or Xyz).
{
[Authorize, RoutePrefix("api/v1/products")]
public class ProductController: BaseApiController
{
[HttpGet, Route("")]
public object GetAll()
{
var products = Database.GetList<Product>(p => p.Owner == User);
var result = products.Select(item => new
{
Id = item.ID,
Name = item.Name,
ImageUrl = item.Image?.Url(),
Category = item.Category
});
return Ok(result);
}
}
Notes:
You can add additional API methods to the same controller as long as they belong to the same concept or sub-system in your application.
public object Add(Product product)
{
if (User == null)
return Unauthorized("Unauthorised access");
if (someValidationCondition)
return BadRequest("My error message");
// TODO: After validation, do what needs to be done (e.g. save in database, etc).
return Ok();
}
Notes: