Web API In ASP.NET

Introduction to Web API

Web API is a programming interface/application type that provides communication or interaction between software applications. Web API is often used to provide an interface for websites and client applications to have data access. Web APIs can be used to access data from a database and save data back to the database. 

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. It is introduced 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 Steps

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

 

Step 4

Create “Employee” table in sql server.

 

Table Script 

Create database Demo    
go    
Use Demo;    
go    
CREATE TABLE [dbo].[Employee](    
    [EmpId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,    
    [Name] [varchar](125) NULL,    
    [Address] [varchar](125) NULL    
    )    
GO

Step 5   

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

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

 

Select "Entity Framework Designer From DataBase" And click Next

 

Select Any Radio Button Based on your requirement and Also change Connection String 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 adding EF in your project.

Step 6

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

Select Referance -> right Click -> Add Referance 

Select Your Class Library Project And click OK.

 

Now Reference Added Successfully.

Step 7

Select Controller Folder And add New Controller.

Right click "Controller" -> Add ->Controller

 

Select Web API 2 Controller Empty Click OK.

 

Step 8

Write Web API Get Method.

"DemoEntities" is a Entity framework class name.

public IEnumerable<Employee> Get()  // It's return All Employee List  
{    
    using (DemoEntities context = new DemoEntities())    
    {    
        return context.Employees.ToList();    
    }    
}    
    
public Employee Get(int Id)   // It's return Employee Base on Employee Id  
{    
    using (DemoEntities context = new DemoEntities())    
    {    
        return context.Employees.FirstOrDefault(e => e.EmpId == Id);    
    }    
} 

Step 9

Run Your project.

Note Before running your project just check "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 framework connection string is not exist in WebConfig file .

So Go to AppConfig file and copy connection string and past in WebConfig file inside connectionStrings tab copy from AppConfig file.

<connectionStrings>  
    <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" />  
</connectionStrings>

past in WebConfig File

<connectionStrings>  
    <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" />  
    <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" />  
</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, then give me your mail Id by commenting. I will Send.


Similar Articles