Skip to main content

How to Build a Web API Using ASP.NET CORE MVC in Minutes


Nowadays we live in a world that is heavily connected, the emergency of cloud computing has simplifies the method of information sharing and access, we’ve evolved from the stage where softwares and applications are just installed and accessed from only one computer to the era of client server, where few system are connected together on a local network, the emergency of internet changed everything with the introduction of web applications, one of the major problem presented by traditional web application is that the design is closed, meaning that the data in the model can only be access through the actions provided by the controller, close systems has become a problem when there is a need to use underlying data by other applications, and that is where Restful API comes to aid. With the emergency of HTTP, HTTP is a powerful platform that exposes data and services and can reach a broad range of clients including browsers, mobile devices, and desktop applications

Create the Web API Project
Listed Below are the API you’ll create
API
Description
Request Body
Response Body
GET/api/task
Get all task
None
Array of Task
GET/api/task/{id}
Get a task by ID
None
Task
POST/api/task
Add a new task
Task
Task
PUT/api/task/{id}
Update an existing task
Task
Task
DELETE/api/task/{id}
Delete a task
None
None

Open Visual Studio, select File menu, > New > Project.

Click on ASP.NET Core Web Application (.NET Core) project template. Name the project Taskapi and click OK.

creating-aspnet-core-project_thumb[1].png

In the New ASP.NET Core Web Application (.NET Core) - Taskapi dialog, click on the Web API template. click O

Add Entity Framework Inmemory Database provider

Install the support for Entity framework Inmemory database provider.
Open the Package Manager Console (PMC): Tools > NuGet Package Manager > Package Manager Console
Enter  PM>  Install-Package Microsoft.EntityFrameworkCore.InMemory
in the PMC.

Create a Model Class

A model is an object that represent the data in your application.

Add a folder named "Models". In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models.

To add a Task class. Right-click the Models folder and select Add > Class. Name the class TAsk and select Add.


public class Task
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public long ID { get; set; }
       public string Tasks { get; set; }
       public bool IsResponse { get; set; }
   }

Add a Database Context
Add the TaskContext class inside the Models folder, which will implement the DbContext class and will be responsible for the interactions between our application and the data provider.



public class TaskAPIContext : DbContext
{
   public TaskAPIContext(DbContextOptions options) : base(options)
   {
   }
   public DbSet<Task> Tasks { get; set; }
}



Create a Repository Interface

Create a Repository class inside the model folder. A repository is an object that encapsulates the data layer.

public interface ITaskRepository
   {
       void Add(Task mytask);
       IEnumerable<Task> GetAll();
       Task GetById(long key);
       void Delete(long key);
       void Update(Task mytask);
   }

Add a Task Repository class that will implement the ITaskRepository interface

public class TaskRepository : ITaskRepository
   {
       private readonly TaskContext _context;

       public TaskRepository(TaskContext context)
       {
           _context = context;

         }

       public IEnumerable<Task> GetAll()
       {
           return _context.Task.ToList();
       }

       public void Add(Task mytask)
       {
           _context.Tasks.Add(item);
           _context.SaveChanges();
       }

       public Task GetById(int ID)
       {
           return _context.Tasks.FirstOrDefault(t => t.ID == ID);
       }

       public void Remove(int ID)
       {
           var entity = _context.Tasks.First(t => t.ID == ID);
           _context.Tasks.Remove(entity);
           _context.SaveChanges();
       }

       

public void Update(Task myTask)
       {

            var tasktoupdate= GetById(myTask.ID);
           _context.Tasks.Update(tasktoupdate);
           _context.SaveChanges();
       }
   }

Register the Repository

In order to inject the repository in the controller, we need to Register it as an injectable service within the ConfigureService in the Startup class. The fun thing about ASP.NET CORE MVC it has an inbuilt Dependency injector, this will save your time because you don’t have to install and configure an external Dependency injector.


public void ConfigureServices(IServiceCollection services)
{
   services.AddDbContext<TaskContext>(opt => opt.UseInMemoryDatabase());

   services.AddMvc();

   services.AddScoped<ITaskRepository, TaskRepository>();
   
}

Add a WebApi Controller

Create a Web API Controller Class in the Controllers folder and name it TaskController.
Replace the auto-generated codes with the following,

[Route("api/[controller]")]
   public class TaskController : Controller
   {
       private readonly ITaskRepository _taskRepository;

       public TaskController(ITaskRepository taskRepository)
       {
           _taskRepository = taskRepository;
       }
[HttpGet]
public IEnumerable<Task> Get()
{
   return _taskRepository.GetAll();
}

[HttpGet("{id}", Name = "GetTask")]
public IActionResult Get(long id)
{
   var item = _taskRepository.GetById(id);
   if (item == null)
   {
       return NotFound();
   }
   return new ObjectResult(item);
}

HttpPost]
public IActionResult Create([FromBody] Task mytask)
{
   if (item == null)
   {
       return BadRequest();
   }

   _taskRepository.Add(item);

   return CreatedAtRoute("GetTask", new { id = mytask.ID }, mytask);
}

[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody] Task mytask)
{
   
   var task = _taskRepository.GetById(id);
   if (task == null)
   {
       return NotFound();
   }

   task.IsResponse = mytask.IsResponse;
   task.Tasks = mytask.Tasks;

   _taskRepository.Update(task);
   return new NoContentResult();
}






[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
   var task = _taskRepository.GetById(id);
   if (task == null)
   {
       return NotFound();
   }

   _taskRepository.Delete(id);
   return new NoContentResult();
}

}

Test your Web Api with Postman
To test your web api program, the status codes stipulated below indicates the success of each http verbs.
On Create(POST), the status code 201 indicates our application has created a new task successfully.

On Update(PUT), the status 200 indicates that the update was successful.

On Delete(DELETE), the status 200 indicate that the update was successful.

Comments

Popular posts from this blog

How to implement RESTful API Versioning in ASP.NET Web API 2 using IHttpRouteConstraint

The only thing constant in life is change, and that is proved everyday in our industry, API’s are cool to extend the functionality of your application and expose it to other developers. The cool thing about IT and software, it’s that things changes quite rapidly and so it’s the technology, hence technology can change and the needs of your organisation can change, hence in order to keep serving this evolving needs and keep been relevant, your api might need to change also. Small changes can be accommodated within the initial version, but changes that will risked breaking the existing code, will required the need for versioning.

Implementing a custom IHttpRouteConstraint

According to msdn, a IHttpRouteConstraint simply Represents a base class route constraint. What then is a route constraint? A route constraint simply gets or sets a dictionary of expressions that specify valid values for a URL parameter.

publicclassApiVersionRouteConstraint : IHttpRouteConstraint
  {

publicApiVersionRouteCo…

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…

How Wrong Use of Data Structure is Costing You Performance

Data structure is a specialise way of storing and organising data so that it can be access efficiently. Today a good chunk of our codes makes use of data structure, and the importance of using the proper data structure for the right job cannot be over emphasised. There are many types of data structure, each one designed to handle the storing and manipulation of data in a specific way. The trick here now is, knowing how to use data structure is not enough but knowing the type to use that’s suits your operation without sacrificing performance.  The determinant factor of the right data structure to use in your program is dependent on some factor like the type of operation you want to perform on the data set like Searching, addition, deletion and access by index.

Comparison between Basic Data Structures

Data Structure Addition Search Deletion Access by Index Array(T[]) O(N) O(N) O(N) O(1) LinkedList(LinkedList<T>) O(1)