Scaffolding Asynchronous in Web API 2 Controllers

Introduction

This article explains the scaffolding of asynchronous Web API 2 Controllers. For this we need Visual Studio 2013. For scaffolding the controller we need to select the "Web API 2 Controller with actions, using Entity Framework". For scaffolding asynchronous Web API controllers use the "use async controller actions" check box that is for scaffolding an asycnchronous Controler in Web API 2.

Now we will explain scaffolding. Scaffolding is just used for automatically generating code in a web application. Visual Studio 2013 has a preinstalled code generator for the Web API. Scaffolding generates the code including the data model class.

  1. Use the following procedure to create a Web API application using Visual Studio 2013.
    • Start Visual Studio 2013.
    • Select "Installed" -> "Web".
    • From the Template window select "ASP.NET Web Application".
    • Click the "OK" button.

      Select Web Application
    • From the ASP.NET Project Window select "Web API".

      Select Web API

    • Click on the "OK" button.
  2. Now we add the Scaffolding Item to the Web API.
    • In the  "Solution Explorer".
    • Right-click on the "Controller" -> "Add" -> "New Scaffold Item".

      Select new Scaffolded Item
    • Open the Scaffold Window to select the type of scaffold, here we select "Web API".

      Select Web API2 Controller With Entity Framework

    • From "Add Controller" enter the name of  the Controller as "ItemsController" and select the check box "Use async controller actions".

      Select Ancy Option

    • Now select the "Model class" and "New Data Context".

      Select Model Class and Data Context

    • After clicking on the "OK" button see the Solution Explorer; there are two files, the first is "ItemsController.cs" in the Controller Folder and the other is "ScaffoldAsyncContext.cs" in the Model Folder.

      Solution explorer

    • Now we open the ItemsController.cs class. We can see that there is some auto-generated code that is inherited from the Model class "Item".

See the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Threading.Tasks;  
  10. using System.Web.Http;  
  11. using System.Web.Http.Description;  
  12. using ScaffoldAsync.Models;  
  13. namespace ScaffoldAsync.Controllers  
  14. {  
  15.     public class ItemsController : ApiController  
  16.     {  
  17.         private ScaffoldAsyncContext db = new ScaffoldAsyncContext();  
  18.         // GET api/Default1  
  19.         public IQueryable<Item> GetItems()  
  20.         {  
  21.             return db.Items;  
  22.         }  
  23.         // GET api/Default1/5  
  24.         [ResponseType(typeof(Item))]  
  25.         public async Task<IHttpActionResult> GetItem(int id)  
  26.         {  
  27.             Item item = await db.Items.FindAsync(id);  
  28.             if (item == null)  
  29.             {  
  30.                 return NotFound();  
  31.             }  
  32.             return Ok(item);  
  33.         }  
  34.         // PUT api/Default1/5  
  35.         public async Task<IHttpActionResult> PutItem(int id, Item item)  
  36.         {  
  37.             if (!ModelState.IsValid)  
  38.             {  
  39.                 return BadRequest(ModelState);  
  40.             }  
  41.             if (id != item.ID)  
  42.             {  
  43.                 return BadRequest();  
  44.             }  
  45.             db.Entry(item).State = EntityState.Modified;  
  46.             try  
  47.             {  
  48.                 await db.SaveChangesAsync();  
  49.             }  
  50.             catch (DbUpdateConcurrencyException)  
  51.             {  
  52.                 if (!ItemExists(id))  
  53.                 {  
  54.                     return NotFound();  
  55.                 }  
  56.                 else  
  57.                 {  
  58.                     throw;  
  59.                 }  
  60.             }  
  61.             return StatusCode(HttpStatusCode.NoContent);  
  62.         }  
  63.         // POST api/Default1  
  64.         [ResponseType(typeof(Item))]  
  65.         public async Task<IHttpActionResult> PostItem(Item item)  
  66.         {  
  67.             if (!ModelState.IsValid)  
  68.             {  
  69.                 return BadRequest(ModelState);  
  70.             }  
  71.             db.Items.Add(item);  
  72.             await db.SaveChangesAsync();  
  73.             return CreatedAtRoute("DefaultApi"new { id = item.ID }, item);  
  74.         }  
  75.         // DELETE api/Default1/5  
  76.         [ResponseType(typeof(Item))]  
  77.         public async Task<IHttpActionResult> DeleteItem(int id)  
  78.         {  
  79.             Item item = await db.Items.FindAsync(id);  
  80.             if (item == null)  
  81.             {  
  82.                 return NotFound();  
  83.             }  
  84.             db.Items.Remove(item);  
  85.             await db.SaveChangesAsync();  
  86.             return Ok(item);  
  87.         }  
  88.         protected override void Dispose(bool disposing)  
  89.         {  
  90.             if (disposing)  
  91.             {  
  92.                 db.Dispose();  
  93.             }  
  94.             base.Dispose(disposing);  
  95.         }  
  96.         private bool ItemExists(int id)  
  97.         {  
  98.             return db.Items.Count(e => e.ID == id) > 0;  
  99.         }  
  100.     }  
  101. } 

We can see in the code above that all the methods are automatically created. There is nothing we need to code ourselves.


Similar Articles