Web API In ASP.NET

Introduction

Web Api Application is programming interface that is used to enable the communication or interaction with software components with each other.

Asp.Net web Api is a framework that make it easy to build HTTP web service that reaches a bored range of clients, including browser, mobile applications, Desktop application and IOTs.
 

What is IOTs

Its internet thinks that have a IP address and communicate with other internet enable devices and objects for example Security System, electronic appliances, desktop, laptop, mobile etc.

What is Restful Services

Rest Stands for Representational state transfer .Its introduce in 2000 by Roy Fielding. In REST architecture, a REST Server simply provides access to resources and the REST client accesses and presents the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource like Text, JSON and XML. JSON is now the most popular format being used in Web Services.

HTTP Methods

The following HTTP methods are most commonly used in a REST based architecture.

  1. GET − Provides a read only access to a resource.
  2. PUT − Used to create a new resource.
  3. DELETE − Used to remove a resource.
  4. POST − Used to update an existing resource or create a new resource. 
REST Constraints

REST constraints are design rules that are applied to establish the distinct characteristics of the REST architectural style.

The formal REST constraints are,

  1. Client-Server
  2. Stateless
  3. Cache
  4. Interface / Uniform Contract
  5. Layered System
  6. Code-On-Demand
Let's Start working in Asp.Net Web Api Project.
 
Step 1 Add New Project

Open VS 2015 -> Click Add Project -> Select web Template -> fill required details.

 

Step 2 

Select Web Api Template and uncheck host checkBox .

 

Step 3

Vs gives some Auto generated code .

Add One Class LIbrary project follow few Step's

Right Click in project Solution -> Add Project -> select visual C# templet -> select Class library

 

Step 4

Create “Employee” table in sql server.

 
Table Script 
  1. Create database Demo  
  2. go  
  3. Use Demo;  
  4. go  
  5. CREATE TABLE [dbo].[Employee](  
  6.     [EmpId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,  
  7.     [Name] [varchar](125) NULL,  
  8.     [Address] [varchar](125) NULL  
  9.     )  
  10. GO  
Step 5   

Select class library project and add Data Entity Modedel in your project.

Right Click Class Library project ->Add->New Item->Select Data template (Left Side)->Ado.Net Entity data model.

 

Select "Entity Framwork Designer From DataBase" And click Next

 

Select Any Radio Button Based on your requriment and Also change Connnection Srring Name and click Next Button.

Note

If Connection String Drop Down Showing null then click "New Connection" Button And follow some instruction

 

Select Any EF version.



Hare choose your table and click Finish Button .It will take some time for addind EF in your project.



Step 6

Select Api Project (Main Project) -> And add Class library referance .

Select Referance -> right Click -> Add Referance 



Select Your Class Library Project And click OK.

 

Now Referace Added Succefully.

Step 7

Select Controller Folder And add New Controller.

Righ click "Controller" -> Add ->Controller

 

Select Web Api 2 Conroller Empty Click OK.

 

Step 8

Write Web Api Get Method .

"DemoEntities" is a Entity framwork class name.
  1. public IEnumerable<Employee> Get()  // It's return All Employee List
  2.        {  
  3.            using (DemoEntities context = new DemoEntities())  
  4.            {  
  5.                return context.Employees.ToList();  
  6.            }  
  7.        }  
  8.   
  9.        public Employee Get(int Id)   // It's return Employee Base on Employee Id
  10.        {  
  11.            using (DemoEntities context = new DemoEntities())  
  12.            {  
  13.                return context.Employees.FirstOrDefault(e => e.EmpId == Id);  
  14.            }  
  15.        }  
Step 9

Run Your project.

Note Bofore running your project just ckeck "Route Name" 

Select App_Start folder -> Open "WebApiConfig.cs" 

 
 
your Routes name is "api"
Step 10

Run It. find your web Api  Method base url is       application Url(current url) +api(route name)+Employee(controller name)  hare my application url is http://localhost:49296 so my api url is http://localhost:49296/api/Employee



once you hit this url got some Error like this because Entity framwork connention string is not exist in WebConfig file .

So Go to AppConfig file and copy connention string and past in WebConfig file inside connectionStrings tab copy from AppConfig file .
  1. <connectionStrings>  
  2.     <add name="DemoEntities" connectionString="metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-TI6NOV0\SQLEXPRESS;initial catalog=Demo;persist security info=True;user id=sa;password=ankit;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  3.   </connectionStrings>  
 past in WebConfig File  
  1. <connectionStrings>  
  2.     <add name="DemoEntities" connectionString="metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-TI6NOV0\SQLEXPRESS;initial catalog=Demo;persist security info=True;user id=sa;password=ankit;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  3.     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApiDemo-20171015011614.mdf;Initial Catalog=aspnet-WebApiDemo-20171015011614;Integrated Security=True" providerName="System.Data.SqlClient" />  
  4.   </connectionStrings>  
 

And Run Again Now I will work.



I hope it's helpful 

Note

I can't upload my project due to project size begin more than 25MB.If you want a project ,than give me your mail Id by commenting.I will Send.

Up Next
    Ebook Download
    View all
    Learn
    View all