CRUD With ASP.NET Web API - Part One

In this article, you will learn about and get answers to these basic things:

  • What is ASP.NET Web API?
  • MVC Controller and API Controller
  • Default API Controller Code
  • What is ASP.NETWeb API Routing?
  • What is HttpResponseMessage?
  • What are FROMURI and FROMBODY?
  • Create Sample Web API project
  • What is WebApiConfig.cs?
  • How to check Web API in the browser
  • CRUD - Create Retrieve Update Delete

We will create a CRUD operation coding and in the next article, i.e., Part 2, we will use it in ASP.NET MVC Web applications.

ASP.NET Web API

API = Application Programming Interface.

ASP.NETWeb API is a framework, which is created to share and collect data. Web APIs are HTTP RESTful services which can be used by various clients like Desktop, Tablet, Mobile.

ASP.NET Web API is created on top of the .NET framework.

Wikipedia Definition - A Web API is an application programming interface for either a web server or a web browser.

Link - https://en.wikipedia.org/wiki/Web_API

RESTful services - https://en.wikipedia.org/wiki/Representational_state_transfer

In this tutorial, we will create a sample Web API.

Step by step

CRUD with Asp.Net Web API

Create a project called MemberWebApiProject.

CRUD with Asp.Net Web API

CRUD with Asp.Net Web API

CRUD with Asp.Net Web API
CRUD with Asp.Net Web API

NOTE
While creating ASP.NET Web API projects, you can see MVC checkbox is selected by default. Now, your screen should look like this.

CRUD with Asp.Net Web API

ASP.NETWeb API controller class is inherited from ApiController classes (System.Web.Http.ApiController) and ASP.NET MVC Controller class inherited from Controller (System.Web.MVC.Controller).

Asp.net Web API works with the following HTTP verbs:

HTTP VERBSDESCRIPTION
Get To get collection(list) or single member. To get the list of members or particular member. http://www.csharpcorner.com/api/values : All Members List  http://www.csharpcorner.com/api/values/1 : Particular member which id = 1 
Post To create a new member detail.
Put To update member detail
Delete To delete a particular member.

Now we will look at the API controller. By default ValuesController.cs is created with the following method.

Default Code of VALUESCONTROLLER.CS

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace MemberWebApiProject.Controllers  
  9. {  
  10.     public class ValuesController : ApiController  
  11.     {  
  12.         //Return Collection of Values  
  13.         // GET api/values  
  14.         public IEnumerable<string> Get()  
  15.         {  
  16.             return new string[] { "value1""value2" };  
  17.         }  
  18.   
  19.         //Return Value  
  20.         // GET api/values/5  
  21.         public string Get(int id)  
  22.         {  
  23.             return "value";  
  24.         }  
  25.   
  26.         //Receive the value and post it  
  27.         // POST api/values  
  28.         public void Post([FromBody]string value)  
  29.         {  
  30.         }  
  31.   
  32.         //Receive the value and update it  
  33.         // PUT api/values/5  
  34.         public void Put(int id, [FromBody]string value)  
  35.         {  
  36.         }  
  37.   
  38.         //Delete the value  
  39.         // DELETE api/values/5  
  40.         public void Delete(int id)  
  41.         {  
  42.         }  
  43.     }  
  44. }  

ASP.NET Web API Routing - Convention Routing

ASP.NET Web API support routing. Web API routing is similar to the ASP.NET MVC action method routing. To configure a new routing for ASP.NET Web API there is a file called “WebApiConfig.cs” which located inside App_Start folder in root path of project. You can create many routings as per your project demand inside webapiconfig.cs file.

Code WebAPIConfig.cs file

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5.   
  6. namespace MemberWebApiProject  
  7. {  
  8.     public static class WebApiConfig  
  9.     {  
  10.         public static void Register(HttpConfiguration config)  
  11.         {  
  12.             // Web API configuration and services  
  13.   
  14.             // Web API routes - To enable attribute base routing.  
  15.             config.MapHttpAttributeRoutes();  
  16.   
  17.   
  18.             config.Routes.MapHttpRoute(  
  19.                 name: "DefaultApi",  
  20.                 routeTemplate: "api/{controller}/{id}",  
  21.                 defaults: new { id = RouteParameter.Optional }  
  22.             );  
  23.         }  
  24.     }  
  25. }  

Attribute Routings

ASP.NETWeb API support attribute routing. Its as same and easy as routing we do on ASP.NET MVC controller action methods.

For more detail about convention vs. attribute routing, refer to the following link,

https://exceptionnotfound.net/attribute-routing-vs-convention-routing/

What are FROMURI and FROMBODY?

FromUri and FromBody are used to transfer the value from client to server. In FromURI attribute, the Web API searches data values in the query string while in FromBody attribute, the Web API searches the data value in the Request body.

Create a table, tblMembers, in your database.

  1. /****** Object:  Table [dbo].[tblMembers]    Script Date: 30-Jul-18 8:01:53 PM ******/  
  2. SET ANSI_NULLS ON  
  3. GO  
  4.   
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7.   
  8. SET ANSI_PADDING ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[tblMembers](  
  12.     [MemberID] [int] IDENTITY(1,1) NOT NULL,  
  13.     [MemberName] [varchar](50) NULL,  
  14.     [PhoneNumber] [varchar](50) NULL,  
  15. PRIMARY KEY CLUSTERED   
  16. (  
  17.     [MemberID] ASC  
  18. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  19. ON [PRIMARY]  
  20.   
  21. GO  
  22.   
  23. SET ANSI_PADDING OFF  
  24. GO  

Right-click on Models folder and insert LINQ TO SQL Classes called MemberDataClasses.dbml.

CRUD with Asp.Net Web API
CRUD with Asp.Net Web API

Double-click on MemberDataClasses.dbml file and press CTRL+ALT+S (Server Explorer).

CRUD with Asp.Net Web API
CRUD with Asp.Net Web API

After clicking on the OK button, your server explorer looks like this.

CRUD with Asp.Net Web API

Now, drag and drop the tblMembers table on MemberDataClasses.dbml canvas.

CRUD with Asp.Net Web API

Now, let us create a new ASP.NET Web API controller called MemberControllers.

Right-click on Controllers folder and select ADD --> NEW ITEM or Press CTRL+ SHIFT + A.

CRUD with Asp.Net Web API

And select Web API Controller Class (v2.1) and give the name “MemberController.cs”.

CRUD with Asp.Net Web API

Code of MemberControllers.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using MemberWebApiProject.Models;  
  8.   
  9. namespace MemberWebApiProject.Controllers  
  10. {  
  11.     public class MemberController : ApiController  
  12.     {  
  13.   
  14.         //Create instance of Linq-To-Sql class as db  
  15.         MemberDataClassesDataContext db = new MemberDataClassesDataContext();  
  16.   
  17.   
  18.   
  19.         //This action method return all members records.  
  20.         // GET api/<controller>  
  21.         public IEnumerable<tblMember> Get()  
  22.         {  
  23.             //returning all records of table tblMember.  
  24.             return db.tblMembers.ToList().AsEnumerable();  
  25.         }  
  26.   
  27.   
  28.   
  29.         //This action method will fetch and filter for specific member id record  
  30.         // GET api/<controller>/5  
  31.         public HttpResponseMessage Get(int id)  
  32.         {  
  33.             //fetching and filter specific member id record   
  34.             var memberdetail = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();  
  35.   
  36.   
  37.             //checking fetched or not with the help of NULL or NOT.  
  38.             if (memberdetail != null)  
  39.             {  
  40.                 //sending response as status code OK with memberdetail entity.  
  41.                 return Request.CreateResponse(HttpStatusCode.OK, memberdetail);  
  42.             }  
  43.             else  
  44.             {  
  45.                 //sending response as error status code NOT FOUND with meaningful message.  
  46.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Code or Member Not Found");  
  47.             }  
  48.         }  
  49.   
  50.   
  51.         //To add a new member record  
  52.         // POST api/<controller>  
  53.         public HttpResponseMessage Post([FromBody]tblMember _member)  
  54.         {  
  55.             try  
  56.             {  
  57.                 //To add an new member record  
  58.                 db.tblMembers.InsertOnSubmit(_member);  
  59.                   
  60.                 //Save the submitted record  
  61.                 db.SubmitChanges();  
  62.   
  63.                 //return response status as successfully created with member entity  
  64.                 var msg = Request.CreateResponse(HttpStatusCode.Created, _member);  
  65.                   
  66.                 //Response message with requesturi for check purpose  
  67.                 msg.Headers.Location = new Uri(Request.RequestUri + _member.MemberID.ToString());  
  68.   
  69.                 return msg;  
  70.             }  
  71.             catch (Exception ex)  
  72.             {  
  73.   
  74.                 //return response as bad request  with exception message.  
  75.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  76.             }  
  77.         }  
  78.   
  79.   
  80.   
  81.         //To update member record  
  82.         // PUT api/<controller>/5  
  83.         public HttpResponseMessage Put(int id, [FromBody]tblMember _member)  
  84.         {  
  85.             //fetching and filter specific member id record   
  86.             var memberdetail = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();  
  87.   
  88.             //checking fetched or not with the help of NULL or NOT.  
  89.             if (memberdetail != null)  
  90.             {  
  91.                 //set received _member object properties with memberdetail  
  92.                 memberdetail.MemberName = _member.MemberName;  
  93.                 memberdetail.PhoneNumber = _member.PhoneNumber;  
  94.                 //save set allocation.  
  95.                 db.SubmitChanges();  
  96.   
  97.                 //return response status as successfully updated with member entity  
  98.                 return Request.CreateResponse(HttpStatusCode.OK, memberdetail);  
  99.             }  
  100.             else  
  101.             {  
  102.                 //return response error as NOT FOUND  with message.  
  103.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Code or Member Not Found");  
  104.             }  
  105.   
  106.   
  107.         }  
  108.   
  109.         // DELETE api/<controller>/5  
  110.         public HttpResponseMessage Delete(int id)  
  111.         {  
  112.   
  113.             try  
  114.             {  
  115.                 //fetching and filter specific member id record   
  116.                 var _DeleteMember = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();  
  117.   
  118.                 //checking fetched or not with the help of NULL or NOT.  
  119.                 if (_DeleteMember != null)  
  120.                 {  
  121.   
  122.                     db.tblMembers.DeleteOnSubmit(_DeleteMember);  
  123.                     db.SubmitChanges();  
  124.   
  125.                     //return response status as successfully deleted with member id  
  126.                     return Request.CreateResponse(HttpStatusCode.OK, id);  
  127.                 }  
  128.                 else  
  129.                 {  
  130.                     //return response error as Not Found  with exception message.  
  131.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member Not Found or Invalid " + id.ToString());  
  132.               }  
  133.             }  
  134.   
  135.             catch (Exception ex )  
  136.             {  
  137.   
  138.                 //return response error as bad request  with exception message.  
  139.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  140.             }  
  141.   
  142.         }  
  143.     }  
  144. }  

What is HttpResponseMessage ?

HttpResponseMessage is a way of returning a message/data from your action.

When you hover on CreateResponse of Request, you can see the following tooltip on the screen.

CRUD with Asp.Net Web API

What is WebApiConfig.cs?

WebApiConfig.cs is a configuration file for setting Web API-related configuration like routing, services, and others.

In the following Web API configuration code, you can see API is prefixed. This API word will create a distinction between normal controller routing and web API routing.

RouteConfig.cs exclusive for Asp.net MVC Controller.

WebApiConfig.cs exclusive for ASP.NET WebApi Controller.

Code of WebApiConfig.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5.   
  6. namespace MemberWebApiProject  
  7. {  
  8.     public static class WebApiConfig  
  9.     {  
  10.         public static void Register(HttpConfiguration config)  
  11.         {  
  12.             // Web API configuration and services  
  13.   
  14.             // Web API routes - To enable attribute base routing.  
  15.             config.MapHttpAttributeRoutes();  
  16.   
  17.   
  18.             config.Routes.MapHttpRoute(  
  19.                 name: "DefaultApi",  
  20.                 routeTemplate: "api/{controller}/{id}",  
  21.                 defaults: new { id = RouteParameter.Optional }  
  22.             );  
  23.         }  
  24.     }  
  25. }  

How to check Web API in browser?

In the following screenshot, you can see URL to check web API.

localhost:52044/api/member : Get All member details.

CRUD with Asp.Net Web API

In the next article, you will come to know how to call and use a Web API and its action methods.