ASP.NET Web API Using MVC And Entity Framework - Part One

Introduction

Web API concepts in different fields and Its implementation using Asp.Net MVC and Entity Framework . Web API Controller connects with Sql Server by Entity Framework. Web API Route can be used in different types of clients Like IOTs. ASP.NET Web API is a framework for building Web API’s, i.e. HTTP based services on top of the .NET Framework. The most common use case for using Web API is for building RESTful services.It has a great role for IOTs stands for Internet Of Things.

WEB API is a best fit to create a resource-oriented services using HTTP/Restful and it works well with MVC-based applications.WEB API can use any text format including XML and is faster than WCF. 

Description

These Web API services can then be Used by below mentioned lists,

  • Browsers
  • Mobile applications
  • Desktop applications

In Client-Server constraint, Client sends a request and the server sends a response. This separation of concerns supports the independent evolution of the client-side logic and server-side logic. In Stateless constraint, the client and the server must be stateless between requests. This means we should not be storing anything on the server related to the client. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.

In Cacheable constraint, the client knows how long this data is good for so that the client does not have to come back to the server for that data over and over again. In Uniform Interface The HTTP verb like GET, PUT, POST, DELETE that is sent with each request tells the API what to do with the resource. Each resource is identified by a specific URI stands for Uniform Resource Identifier.

Why Asp.Net Web API faster than WCF?

WCF was created to develop SOAP-based services and bindings. Since WCF is SOAP-based, which uses standard XML schema over HTTP, it could lead to slower performance. WEB API is a better choice for simpler, lightweight services. WEB API can use any text format including XML and is faster than WCF. WEB API doesn’t require any data contracts and doesn’t require configurations to the level of WCF.

Refer

To know more about Entity Framework, please visit my profile as mentioned below.

Way To Source Code

Steps To Be Followed,

Step 1

Create a table named Employee2 using the below script.

  1. SET ANSI_NULLS ON  
  2. GO  
  3.   
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6.   
  7. CREATE TABLE [dbo].[Employee2](  
  8.     [EmployeeID] [int] IDENTITY(1,1) NOT NULL,  
  9.     [FirstName] [nvarchar](50) NOT NULL,  
  10.     [LastName] [nvarchar](50) NOT NULL,  
  11.     [EmailID] [nvarchar](200) NULL,  
  12.     [City] [nvarchar](50) NULL,  
  13.     [Country] [nvarchar](50) NULL,  
  14. PRIMARY KEY CLUSTERED   
  15. (  
  16.     [EmployeeID] ASC  
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  18. ON [PRIMARY]  
  19.   
  20. GO 
Now Insert some dummy records into that table using the below script. 
  1. GO  
  2. SET IDENTITY_INSERT [dbo].[Employee2] ON   
  3.   
  4. GO  
  5. INSERT [dbo].[Employee2] ([EmployeeID], [FirstName], [LastName], [EmailID], [City], [Country]) VALUES (1, N'Satyaprakash', N'Samantaray', N'[email protected]', N'Bengaluru', N'India')  
  6. GO  
  7. INSERT [dbo].[Employee2] ([EmployeeID], [FirstName], [LastName], [EmailID], [City], [Country]) VALUES (2, N'Satya', N'Saman', N'[email protected]', N'Bhubaneswar', N'India')  
  8. GO  
  9. INSERT [dbo].[Employee2] ([EmployeeID], [FirstName], [LastName], [EmailID], [City], [Country]) VALUES (3, N'sa', N'sa', N'[email protected]', N'bangalore', N'india')  
  10. GO  
  11. SET IDENTITY_INSERT [dbo].[Employee2] OFF  
  12. GO 

Step 2

Add Entity data model named "Satyadatabasemodel.edmx". Inside that model name create entity name "CrystalGranite2016Entities". Inside Model already a autogenerate class Employee.cs as I renamed it Employee2 to Employee same as database object like Table Employee2 with related variables.
 
Code Ref
  1. namespace SatyaWebApi   
  2. {   
  3.     using System;   
  4.     using System.Collections.Generic;   
  5.        
  6.     public partial class Employee   
  7.     {   
  8.         public int EmployeeID { getset; }   
  9.         public string FirstName { getset; }   
  10.         public string LastName { getset; }   
  11.         public string EmailID { getset; }   
  12.         public string City { getset; }   
  13.         public string Country { getset; }   
  14.     }   
  15. }  
Step 3

Create an empty API Controller called "SatyaController.cs". Then, I added a new action to the API Controller for fetch data fromdatabaseand return to the client application.

Code Ref
  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 SatyaWebApi.Controllers   
  9. {   
  10.     public class SatyaController : ApiController   
  11.     {   
  12.            
  13.         public HttpResponseMessage Get()   
  14.         {   
  15.             List<Employee> allEmp = new List<Employee>();   
  16.             using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())    
  17.             {   
  18.                 allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();    
  19.                 HttpResponseMessage response;   
  20.                 response = Request.CreateResponse(HttpStatusCode.OK, allEmp);   
  21.                 return response;   
  22.             }   
  23.         }   
  24.     }   
  25. }  
Code Description

I added strongly typed list of objects that can be accessed by Index.
  1. List<Employee> allEmp = new List<Employee>(); 
Here i added action for get to fetch data from database and return to the client.
  1. public HttpResponseMessage Get()   
  2. {   
  3.    //code here....   

Here CrystalGranite2016Entities is our DataContext.
  1. using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())    
  2. {   
  3.     //code here....   

Here i have added Linq code for fetch data.
  1. List<Employee> allEmp = new List<Employee>();        
  2. allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();    
HttpResponseMessage represents http response message. Then, create an HttpResponseMessage wired up to the associated HttpRequestMessage. The HttpStatusCode contains the value of status code defined for HTTP. All these classes and enum shoud need below namespaces.  
  1. using System.Net;   
  2. using System.Net.Http;   
  3. using System.Web.Http; 
Step 4

Then, check connectionstring inside web.config file as it is autogenerated during creation of Entity Data Model (.edmx file) .
  1. <connectionStrings>   
  2.     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SatyaWebApi-20180326100928.mdf;Initial Catalog=aspnet-SatyaWebApi-20180326100928;Integrated Security=True" providerName="System.Data.SqlClient" />   
  3.     <add name="CrystalGranite2016Entities" connectionString="metadata=res://*/Satyadatabasemodel.csdl|res://*/Satyadatabasemodel.ssdl|res://*/Satyadatabasemodel.msl;provider=System.Data.SqlClient;provider connection string="data source=SODN-PAVILION\SQLEXPRESS;initial catalog=CrystalGranite2016;user id=sa;password=satya;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />   
  4.   </connectionStrings> 
Step 5

Check the Reference folder and findout two assembly (.Dll files) are related to entity framework related information.
  • EntityFramework
  • EntityFramework.SqlServer 
Step 6

Check out the WebApiConfig.cs to find out Web API routes or URL path of WEB API to get records in XML format.

Code Ref
  1. config.Routes.MapHttpRoute(  
  2.    name: "DefaultApi",  
  3.    routeTemplate: "api/{controller}/{id}",  
  4.    defaults: new { id = RouteParameter.Optional }  
  5. );  
Code Description

Here, path should be http://site_name/api/API_Controller_Name.

OUTPUT

The Web API Route is : http://localhost:47250/api/satya .Here satya is name of API Controller name. I got all records in XML format in browser.

 
WEB API is a better choice over WCF and Web Services 

WCF
  1. WCF support multiple transport protocols (HTTP, HTTPS, Name Pipes, MSMQ, TCP, UDP, and custom transports) and allows switching between them.
  2. WCF doesn't support MVC features
  3. The Extension of WCF service is .svc.
  4. WCF support XML , JSON and ATOM Data format.
  5. WCF Supports Request-Reply, One Way, and Duplex message exchange patterns.
  6. WCF send the data asynchronously from one endpoint service to another service
  7. WCF can be hosted with in the application or on IIS or using window service.
  8. WCF Uses DataContractSerializer which is better in Performance as Compared to XmlSerializer.
  9. It can be hosted with in the applicaion or on IIS or using window service.
  10. Content format is SOAP+XML.
  11. Its Service interface is Service contracts.
  12. State management is Stateless with Per Call.
  13. Caching mechanism is Handled by application.
  14. Error handling type Faults, behaviors.
  15. Types is Opt-in.
Asp.Net Web API
  1. The ASP. NET Web API is a framework that uses the HTTP services and makes it easy to provide the response to the client request.
  2. Web API are a simple class file with .cs (C#) extension
  3. Web API can be hosted within the application or on IIS
  4. It is open source and can be consumed by any client that understands XML or JSON.
  5. It support the MVC feature such as routing, controllers , Action Results, model binders, IOC container or dependency injection , unit testing that makes it more simple and robust.
  6. HTTP is request/Response but additional patterns can be supported through SignalRand WebSockets integration.
  7. Web API light weight architecture and good for devices which have limited bandwidth like smart phones.
  8. Content format is Any media format.
  9. Its Service interface is URL Patterns, HTTP methods.
  10. State management is Stateless.
  11. Caching mechanism is Built in to HTTP Prefer application control.
  12. Error handling type HTTP status codes filters, exceptions.
  13. Types is Opt-out.
Web Service
  1. Web Service is based on SOAP and return data in XML format only.
  2. SOAP(Simple Object Access Protocol) defines its own security.
  3. The extension of web service is .asmx
  4. Web Service support only HTTP protocol
  5. Web Service doesn't support MVC features
  6. It can be hosted only on IIS.
SUMMARY
  • What is Asp.Net Web API.
  • How to implement using Entity Framework and MVC.
  • Web API in Real-Time Scenario.
  • Benefits Of Asp.Net Web API.


Similar Articles