Introduction
The ASP. Net Web API is a framework for building HTTP services that can consume a wide range of clients including browsers, mobiles, iPhones, 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 readme file. Startup.cs contains the 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",
//"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
Next, open Startup.cs with the code shown below.
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
app.UseWelcomePage();
// app.UseMvc();
}
}
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",
// ADD
"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; // add new
namespace WebApplication1
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
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;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApplication1.Controllers
{
//[Route("api/[controller]")]
public class HomeController : Controller
{
// GET: /<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;
// return new string[] {""}
}
//[HttpGet("{id:int}", Name = "GetByIdRoute")]
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;
}
}
// [HttpDelete("{id}")]
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 template 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() {} // [HttpGet]
public IActionResult GetById(int id) {} // [HttpGetById]
public void CreateCustomer([FromBody] Customer item) {} // [HttpPost]
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.