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.
- "dependencies": {
- "Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
- "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
-
- },
Next, open Startup.cs with the code shown below.
- public class Startup
- {
- public void Configure(IApplicationBuilder app)
- {
-
- app.UseWelcomePage();
-
- }
- }
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.
- "dependencies": {
- "Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
- "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
-
- "Microsoft.AspNet.Mvc": "6.0.0-beta1"
- },
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.
- using System;
- using Microsoft.AspNet.Builder;
- using Microsoft.AspNet.Http;
- using Microsoft.Framework.DependencyInjection;
-
- namespace WebApplication1
- {
- public class Startup
- {
- public void Configure(IApplicationBuilder app)
- {
-
- app.UseWelcomePage();
- app.UseMvc();
- }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
- }
- }
Add a Model
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace WebApplication1.Model
- {
- public class customer
- {
- public int customerid { get; set; }
- [Required]
- public string name { get; set; }
-
- }
- }
Add Controller
- using Microsoft.AspNet.Mvc;
- using System.Collections.Generic;
- using System.Linq;
- using WebApplication1.Model;
-
-
-
-
- namespace WebApplication1.controllers
- {
-
- public class HomeController : Controller
- {
-
- static readonly new List<customer> _items = new List<customer>()
- {
-
- new customer { customerid = 1, name = "atul rawat" },
- new customer { customerid = 2, name = "shridhar" },
- };
- public IEnumerable<customer> Get()
- {
-
- return _items;
-
-
-
- }
-
- public IActionResult GetById(int id)
- {
- var its = _items.FirstOrDefault(x => x.customerid == id);
- if (its == null)
- {
- return HttpNotFound();
- }
-
- return new ObjectResult(its);
- }
- public void createcustomer([FromBody] customer item)
- {
-
- if (!ModelState.IsValid)
- {
- Context.Response.StatusCode = 400;
- }
- else
- {
- item.customerid = 1 + _items.Max(x => (int?)x.customerid) ?? 0;
- _items.Add(item);
-
- string url = Url.RouteUrl("GetByIdRoute", new { id = item.customerid },
- Request.Scheme, Request.Host.ToUriComponent());
-
- Context.Response.StatusCode = 201;
- Context.Response.Headers["Location"] = url;
- }
-
- }
-
- public IActionResult DeleteItem(int id)
- {
- var item = _items.FirstOrDefault(x => x.customerid == id);
- if (item == null)
- {
- return HttpNotFound();
- }
- _items.Remove(item);
- return new HttpStatusCodeResult(204);
- }
-
- }
- }
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.
- [Route("api/[controller]")]
HTTP Methods
The [HttpGet], [HttpPost] and [HttpDelete] attributes define the HTTP methods for the controller actions.
- public IEnumerable<customer> Get(){}
- public IActionResult GetById(int id){}
- public void createcustomer([FromBody] customer item){}
- public IActionResult DeleteItem(int id){}
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.