Create Web API in MVC 6

Introduction to Web API

The ASP. Net Web API is a framework for building HTTP services that can consume a wide range of clients including browsers, mobiles, iPhone, tablets and so on. An API must be compatible with modern browsers to use these services in a simple way. We can easily expose your service data to the browser as well as modern apps in a fast and simple manner.


Need of Web API

If we need a Web Service and do not need SOAP then the ASP.Net API is the best choice. It builds simple non-SOAP based HTTP services on top of the existing WCF message Pipeline. The ASP.Net Web API is based on HTTP and is easy to define. It is open source. It is lightweight architecture and better for devices that have limited bandwidth like smartphones.
 
Create a simple Web API in ASP. NET MVC 6

Start Visual Studio 2015 Preview. From the File menu, select New > Project. In the New Project dialog, click Templates > Visual C# > Web and select the ASP. NET Web Application project template. Name the project "WebApplication1" and click OK.


In the
New ASP.NET Project dialog, select the "ASP.NET 5.0 Empty" template.
 
 

The project includes the following files:
  
 
 
Global.json contains the solution settings. project.json contains the project settings. Project_Readme.html is a read me file. Startup.cs contains configuration code.
 
Open the Project.json file. Add the class libraries to the dependencies section.
  1. "dependencies": {  
  2.         "Microsoft.AspNet.Server.IIS""1.0.0-beta1",  
  3.         "Microsoft.AspNet.Diagnostics""1.0.0-beta1",  
  4.         //"Microsoft.AspNet.Mvc": "6.0.0-beta1"   
  5.     },  
Next, open Startup.cs with the code shown below.
  1. public class Startup  
  2. {  
  3.        public void Configure(IApplicationBuilder app)  
  4.        {  
  5.            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
  6.            app.UseWelcomePage();  
  7.           // app.UseMvc();  
  8.        }
  9. }  
After debugging Visual Studio launch a browser and navigate to http://localhost:port/.
 
 

Create a Web  API

In this part we will create a Web API to manage the list of customer items. First we need to add ASP.Net MVC6 to the app.
Add the MVC6 package to the list of dependencies in Project.json. Let us see the code below.
  1. "dependencies": {  
  2.         "Microsoft.AspNet.Server.IIS""1.0.0-beta1",  
  3.         "Microsoft.AspNet.Diagnostics""1.0.0-beta1",  
  4.         //ADD  
  5.         "Microsoft.AspNet.Mvc""6.0.0-beta1"   
  6.     },   
Next, add MVC to the request pipeline in Startup.cs.
  • Add Using statement for Microsoft.Framework.DependencyInjection.

  • Add the following method to the Startup class.
  1. using System;  
  2. using Microsoft.AspNet.Builder;  
  3. using Microsoft.AspNet.Http;  
  4. using Microsoft.Framework.DependencyInjection;//add new  
  5.   
  6. namespace WebApplication1  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public void Configure(IApplicationBuilder app)  
  11.         {  
  12.             // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
  13.             app.UseWelcomePage();  
  14.            app.UseMvc();  
  15.         }  
  16.   
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.             services.AddMvc();  
  20.         }  
  21.     }  
  22. }  
Add a Model
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace WebApplication1.Model  
  5. {  
  6.     public class customer  
  7.     {  
  8.         public int customerid { getset; }  
  9.         [Required]  
  10.         public string name { getset; }  
  11.   
  12.     }  
  13. }  
Add Controller
  1. using Microsoft.AspNet.Mvc;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using WebApplication1.Model;  
  5.   
  6.   
  7. // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860  
  8.   
  9. namespace WebApplication1.controllers  
  10. {  
  11.     //[Route("api/[controller]")]  
  12.     public class HomeController : Controller  
  13.     {  
  14.         // GET: /<controller>/  
  15.         static readonly new List<customer> _items = new List<customer>()  
  16.         {  
  17.   
  18.                   new  customer  { customerid = 1, name = "atul rawat" },  
  19.                   new customer { customerid = 2, name = "shridhar" },  
  20.         };  
  21.         public IEnumerable<customer> Get()  
  22.         {  
  23.   
  24.             return _items;  
  25.   
  26.             // return new string[] {""}  
  27.   
  28.         }  
  29.         //[HttpGet("{id:int}", Name = "GetByIdRoute")]  
  30.         public IActionResult GetById(int id)  
  31.         {  
  32.             var its = _items.FirstOrDefault(x => x.customerid == id);  
  33.             if (its == null)  
  34.             {  
  35.                 return HttpNotFound();  
  36.             }  
  37.   
  38.             return new ObjectResult(its);  
  39.         }  
  40.         public void createcustomer([FromBody] customer item)  
  41.         {  
  42.   
  43.             if (!ModelState.IsValid)  
  44.             {  
  45.                 Context.Response.StatusCode = 400;  
  46.             }  
  47.             else  
  48.             {  
  49.                 item.customerid = 1 + _items.Max(x => (int?)x.customerid) ?? 0;  
  50.                 _items.Add(item);  
  51.   
  52.                 string url = Url.RouteUrl("GetByIdRoute"new { id = item.customerid },  
  53.                     Request.Scheme, Request.Host.ToUriComponent());  
  54.   
  55.                 Context.Response.StatusCode = 201;  
  56.                 Context.Response.Headers["Location"] = url;  
  57.             }  
  58.   
  59.         }  
  60.        // [HttpDelete("{id}")]  
  61.         public IActionResult DeleteItem(int id)  
  62.         {  
  63.             var item = _items.FirstOrDefault(x => x.customerid == id);  
  64.             if (item == null)  
  65.             {  
  66.                 return HttpNotFound();  
  67.             }  
  68.             _items.Remove(item);  
  69.             return new HttpStatusCodeResult(204);   
  70.         }  
  71.         
  72.     }  
  73. }  
Explanation of the preceding code
In this part I will describe the Homecontroller class.
  
Routing

The routing attribute defines a URL templates of the controller.
  1. [Route("api/[controller]")]  
HTTP Methods

The [HttpGet], [HttpPost] and [HttpDelete] attributes define the HTTP methods for the controller actions.
  1. public IEnumerable<customer> Get(){}  //[HttpGet]  
  2. public IActionResult GetById(int id){} //[HttpGetbyid}  
  3. public void createcustomer([FromBody] customer item){}/ / [Http Post]  
  4. public IActionResult DeleteItem(int id){} //[HttpDelete]  
The {customerid:int} int constrains the variable to match an integer so the URLs will match.
http://localhost/api/home/1
http://localhost/api/home/42
  
Summary
 
In this article we have created a Web API in MVC 6 using a model, controller and HTTP methods.

Up Next
    Ebook Download
    View all
    Learn
    View all