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
Create a project called MemberWebApiProject.
NOTE
While creating ASP.NET Web API projects, you can see MVC checkbox is selected by default. Now, your screen should look like this.
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 VERBS | DESCRIPTION |
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace MemberWebApiProject.Controllers
- {
- public class ValuesController : ApiController
- {
-
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
-
- public string Get(int id)
- {
- return "value";
- }
-
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
-
- public void Delete(int id)
- {
- }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
-
- namespace MemberWebApiProject
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.MapHttpAttributeRoutes();
-
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
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.
- /****** Object: Table [dbo].[tblMembers] Script Date: 30-Jul-18 8:01:53 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[tblMembers](
- [MemberID] [int] IDENTITY(1,1) NOT NULL,
- [MemberName] [varchar](50) NULL,
- [PhoneNumber] [varchar](50) NULL,
- PRIMARY KEY CLUSTERED
- (
- [MemberID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- GO
Right-click on Models folder and insert LINQ TO SQL Classes called MemberDataClasses.dbml.
Double-click on MemberDataClasses.dbml file and press CTRL+ALT+S (Server Explorer).
After clicking on the OK button, your server explorer looks like this.
Now, drag and drop the tblMembers table on MemberDataClasses.dbml canvas.
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.
And select Web API Controller Class (v2.1) and give the name “MemberController.cs”.
Code of MemberControllers.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using MemberWebApiProject.Models;
-
- namespace MemberWebApiProject.Controllers
- {
- public class MemberController : ApiController
- {
-
-
- MemberDataClassesDataContext db = new MemberDataClassesDataContext();
-
-
-
-
-
- public IEnumerable<tblMember> Get()
- {
-
- return db.tblMembers.ToList().AsEnumerable();
- }
-
-
-
-
-
- public HttpResponseMessage Get(int id)
- {
-
- var memberdetail = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();
-
-
-
- if (memberdetail != null)
- {
-
- return Request.CreateResponse(HttpStatusCode.OK, memberdetail);
- }
- else
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Code or Member Not Found");
- }
- }
-
-
-
-
- public HttpResponseMessage Post([FromBody]tblMember _member)
- {
- try
- {
-
- db.tblMembers.InsertOnSubmit(_member);
-
-
- db.SubmitChanges();
-
-
- var msg = Request.CreateResponse(HttpStatusCode.Created, _member);
-
-
- msg.Headers.Location = new Uri(Request.RequestUri + _member.MemberID.ToString());
-
- return msg;
- }
- catch (Exception ex)
- {
-
-
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
-
-
-
-
-
- public HttpResponseMessage Put(int id, [FromBody]tblMember _member)
- {
-
- var memberdetail = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();
-
-
- if (memberdetail != null)
- {
-
- memberdetail.MemberName = _member.MemberName;
- memberdetail.PhoneNumber = _member.PhoneNumber;
-
- db.SubmitChanges();
-
-
- return Request.CreateResponse(HttpStatusCode.OK, memberdetail);
- }
- else
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Code or Member Not Found");
- }
-
-
- }
-
-
- public HttpResponseMessage Delete(int id)
- {
-
- try
- {
-
- var _DeleteMember = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();
-
-
- if (_DeleteMember != null)
- {
-
- db.tblMembers.DeleteOnSubmit(_DeleteMember);
- db.SubmitChanges();
-
-
- return Request.CreateResponse(HttpStatusCode.OK, id);
- }
- else
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member Not Found or Invalid " + id.ToString());
- }
- }
-
- catch (Exception ex )
- {
-
-
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
-
- }
- }
- }
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.
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
-
- namespace MemberWebApiProject
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.MapHttpAttributeRoutes();
-
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
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.
In the next article, you will come to know how to call and use a Web API and its action methods.