Create Web API in Code First Model
ASP.NET Web API is a framework that is used to create HTTP related services. Web API is open source and platform or device independent. Traditional web services are SOAP based, but web API is non SOAP based. It helps us to transfer data with a limited internet bandwidth. This article explains how to create web API in ASP.NET using code first model, how to call a web API. This can be summarized as like:
- Table Creations
- Web API Project Creations
- Host Web API
- Call Web API
Before starting we need to learn some basic knowledge on ASP.NET Web API. We can get it from the internet easily. We can perform numerous tasks by using Web API. Let’s consider a table in the database and we want to perform the basic DML operations on that table through web API. Here, we will create a web API which will perform CRUD operations.
Table Creations
Create a Database in the SQL Server named “TestDB”. Create a “Students” table in the database. We can use the following SQL scripts:
Create a Database in the SQL Server named “TestDB”. Create a “Students” table in the database. We can use the following SQL scripts:
CREATE TABLE [dbo].[Students]( [StudentID] [int] IDENTITY(1,1) NOT NULL, [StudentName] [nvarchar](150) NULL, [Address] [nvarchar](200) NULL, [Phone] [nvarchar](50) NULL, CONSTRAINT [PK_member] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Web API Project Creations
We can create web API as a separate project or with an ASP.NET MVC project. Let’s start with separate project. In order to implement this we need to install Visual Studio 2010/2012, MVC 4.0. All are available on the internet. Here Visual Studio 2010 is used. All the steps are given bellow:
Step1
Open Visual Studio and click “New Project” or File -> New Project. In the New Project dialog box:
Open the Visual C# templates
Select the template ASP.NET MVC 4 Web Application
Set the project name to MyWebAPI
Set the disk location to something like C:\TestProject
Click OK
A new window will appear for selecting a sub-template. Multiple sub-options are available like Empty, Internet Application, Web API etc.
Choose “Web API” and click OK button
We can create web API as a separate project or with an ASP.NET MVC project. Let’s start with separate project. In order to implement this we need to install Visual Studio 2010/2012, MVC 4.0. All are available on the internet. Here Visual Studio 2010 is used. All the steps are given bellow:
Step1
Open Visual Studio and click “New Project” or File -> New Project. In the New Project dialog box:
Open the Visual C# templates
Select the template ASP.NET MVC 4 Web Application
Set the project name to MyWebAPI
Set the disk location to something like C:\TestProject
Click OK
A new window will appear for selecting a sub-template. Multiple sub-options are available like Empty, Internet Application, Web API etc.
Choose “Web API” and click OK button
A default ASP.NET MVC 4 Web API template project will be created. It is an MVC application template, so we will find “Model”, “View” and “Controller” folders in the Solution Explorer. An index page is also created under View folder. Generally we don’t need to crate no more views. If we run this application we will get basic ASP.NET Web API interface.
Step2
Create a connection string in Web.config file. Add the following element to the element in Web.config file:
Create a connection string in Web.config file. Add the following element to the element in Web.config file:
<add name="DBContext" connectionString=".;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=sa123" providerName="System.Data.SqlServerCe.4.0"/>
Step3
Create a database model.
In the Solution Explorer right-click the Models folder and select “Add” and “Class”.
Name the class Students.cs and click Add.
Write the following codes inside the class.
Create a database model.
In the Solution Explorer right-click the Models folder and select “Add” and “Class”.
Name the class Students.cs and click Add.
Write the following codes inside the class.
[Key] public int StudentID { get; set; } [Required] public string StudentName { get; set; } public string Address { get; set; } public string Phone { get; set; }
Class name should as like our table name. In our Students table we have StudentID, StudentName, Address, Phone columns. StudentID is integer and others fields are varchar type.
In our table StudentID is primary key. That’s why have used [Key] to clarify that it is the Primary Key. If the field name is “ID” then we don’t need to use [Key]. [Required] is used for required filed validation. That means StudentName is mandatory.
In our table StudentID is primary key. That’s why have used [Key] to clarify that it is the Primary Key. If the field name is “ID” then we don’t need to use [Key]. [Required] is used for required filed validation. That means StudentName is mandatory.
The following namespace or reference is required for ASP.NET MVC application using code first model.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
Step4
Need to create a Context class inside the Models folder.
In the Solution Explorer, right-click the Models folder, and select “Add” and Class.
Name the class “DBContext.cs” and click Add.
System.Data.Entity;
Edit the class as like:
Need to create a Context class inside the Models folder.
In the Solution Explorer, right-click the Models folder, and select “Add” and Class.
Name the class “DBContext.cs” and click Add.
System.Data.Entity;
Edit the class as like:
public class DBContext : DbContext { public DbSet<Students> Students { get; set; } }
The following namespace or reference is may required for ASP.NET MVC Application using Code First Model.
System.Data.Entity;
System.Data.Entity;
DbContext is a built class of .Net. DbContext is a lightweight version of the ObjectContext class. DbContext requires a lot less code for the same kind of functionality. ObjectContext EF V4.0 and DbContext EF V4.1
Step5
We need to create a Controller for the Student. We can create a Controller by following steps:
Re-Build the project from the menu.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to StudentController
Select template: API controller with read/write actions, using Entity Framework
Select model class: Students (MyWebAPI.Models)
Select data context class: DBContext (MyWebAPI.Models)
Click Add
We need to create a Controller for the Student. We can create a Controller by following steps:
Re-Build the project from the menu.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to StudentController
Select template: API controller with read/write actions, using Entity Framework
Select model class: Students (MyWebAPI.Models)
Select data context class: DBContext (MyWebAPI.Models)
Click Add
Visual Studio will create “StudentController.cs” file in the Controllers folder and StudentController Class. This class inherits ApiController class which is responsible for ASP.NET Web API. This class contains all the necessary methods that perform CRUD operations.
We may face a common errors “Context Has Changed Since the Database Was Created”.
To solve this error include the namespace “MyWebAPI.Models” and writhe the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer(null);
To solve this error include the namespace “MyWebAPI.Models” and writhe the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer(null);
Call Web API
Our web API is now created and ready for deployment. We can now host it in the IIS and can use with our applications. There are some HTTP methods to access web API. Some common HTTP methods are given bellow:
GET : used to get/select data
POST : used to create a new data
PUT : used to update the existing data
DELETE : used to Delete the data
Our web API is now created and ready for deployment. We can now host it in the IIS and can use with our applications. There are some HTTP methods to access web API. Some common HTTP methods are given bellow:
GET : used to get/select data
POST : used to create a new data
PUT : used to update the existing data
DELETE : used to Delete the data
We can also test our web API from our local machine. Just run the application, welcome window will appear. Insert some sample data in the Students table. In order to run Student controller change the URL as http://localhost:xxxx/api/student. All the student lists will be appeared. For a particular student record (Student ID=2) change the URL as http://localhost:xxxx/api/student/2.
From the web browser we can test only GET and DELETE methods. To check all the methods we can use third party tools. Lot s of free tools is available. Fiddler is one of them. We can download it from its site. Internet explorer latest version also provides this facility.
That’s all about web API.
No comments