Thursday, April 5, 2018

ASP.NET WEB API Programming


ASP.NET WEB API Programming.

In this blog post we will see a sample example to jump start ASP.NET WEB API Programming.

Before starting we will understand few important and basic questions regarding the existence of the ASP.NET web api programming.


Question 1 : Is ASP.NET WEB API is replacement of WCF ?


No,It is not true that web api has replaced WCF, but it's way different than WCF, where WCF follows SOAP based message formatting and web api builds services which are non-SOAP based and returns plain XML or JSON string etc. and web api transport data over HTTP only unlike WCF, which accepts different protocols for transmitting data over HTTP, TCP, MSMQ, Named pipes.etc.  

Question 2 : WCF RESTful Service Vs ASP.NET Web API?

Both WCF REST and ASP.NET Web API follows the REST architecture but have following differences:

ASP.NET Web API
  • When Compare to WCF REST, Web API supports full features of HTTP.
  • Its possible to host Web API in IIS as well as in an application and can be self host.
WCF REST
  • Microsoft released “WebHttpBinding” for creating WCF RESTful Services.
  • HTTP Methods are mapped to attributes, for example, “WebGet” for GET method and “WebInvoke” for POST.
Question 3 : Difference between MVC & ASP.NET Web API?
In our previous posts we have discussed that purpose of Web API framework is to generate HTTP services that reaches more clients by generating data in raw format, for example, plain XML or JSON string.So, ASP.NET Web API creates simple HTTP services that renders raw data.

Whereas  ASP.NET MVC framework is used to develop web applications that generates Views as well as data. 

Let's start Implementing WEB API in .NET Framework


1) Open Visual studio (I have used Visual Studio 2017 Version)

2) Goto File-> New -> Project




3) Select Asp.net web application  from the list as shown in the above image.

4) Enter a name for your application click, then click Ok.

5) In the next window select empty template to create stand alone application.




6) Goto Solution Explorer, Right click on solution folder and select "Manage Nuget Packages".


7) Select Browse Tab in the window and enter search text as "webapi" and select "Microsoft.ASPNET.Webapi" from the list then click on Install/Download button.



8) After installing webapi package, goto solution explorer and add two folders for controllers      and configuration file. Name it as "Controllers" and "Configuration".

9) Goto Configuration folder and add a configuration file and name it as                                      "HelloWorldWebAPIConfiguration.cs"




10) add name namespace System.Web.Http in "HelloWorldWebAPIConfiguration.cs" class

11) add the following lines of code in the configuration



using System.Web.Http;

namespace HelloWorldWebAPI.Configuration
{
public class HelloWorldWebAPIConfiguration
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new {id = RouteParameter.Optional
           });
}
}
}

12) Add Global.asax file ,go to project root folder and right click then select new item from the new item window select Global Application Class then click Ok.





13) We need to configure web api routes when application starts. add below line in                       application_start() event of global.asax 


  GlobalConfiguration.Configure(HelloWorldWebAPIConfiguration.Register);



Note : Web API is configured only using code based configuration using GlobalConfiguration class. The Configure() method requires a callback method where you have configured your Web API.Thus, when application starts it will call Application_Start event which in turn calls HelloWorldWebAPIConfiguration.Register() method to configure your Web API.



14) Now add Api Controller by right clicking on controller folder then select add  -->
      New Item ->  select api controller template, Provide a name for the api controller.  


15) Web API Controller: Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.

16) Remove predefined action methods from the class.. then include the below lines of code in the controller class

public string Get()
        {
            return "Hello World, Welcome to Web API";
        }

17) Build & Run your application and goto address bar in the browser and enter below url 

http://localhost:62107/api/HellowWorldWebApi

note : change port number according your application...

then you will see the below result in the XML format




Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.


When we add a controller we can see the controller class loaded with pre defined action methods , and Controller class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete. see below picture.





Based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), Web API confirms which Web API controller and action method to call for execution e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API.


If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.

[HttpGet] public IEnumerable<string> Values() { return new string[] { "value1", "value2" }; }



Web API Controller Characteristics:


  • Controller class must be derived from System.Web.Http.ApiController class.
  • It can be created under any folder in the project's root folder. It is recommended to create controller classes in the Controllers folder as per the convention.
  • Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.
  • Return type of an action method can be any primitive or complex type.

Interview Questions on WEB API  

(comment your answers in the comment box)

1) Web API supports which of the following protocol?

a) HTTP
b) TCP

c) SOAP
d) all of the above

2) Which of the following .NET framework supports Web API?

a) .NET 3.0

b) .NET 3.5

c) .NET 2.0

d) .NET 4.0

3) Which of the following types of routing is supported in Web API 2?

a) Attribute Routing

  b)Convention-based Routing

c)All of the above

d)None of the above


Tuesday, April 3, 2018

Introduction to ASP.NET WEB API


What is ASP.NET WEB API ?


WEB API is a framework for building HTTP services that can be accessed across broad range of devices and platforms including browsers, mobile devices,IOT(Internet of things) devices, desktop devices and cross platforms. It is perfect for building restful services.though It can be used to create services which are not restful.Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol.It is very much similar to ASP.Net MVC pattern as it contains MVC like features controllers, action results, routing, filters and model. ASP .Net Web API is added advantage to the ASP.Net Framework. and web api actions(methods) are called by HTTP verbs(GET,POST,PUT,DELETE).

What is API ?

API : API stands for Application Program Interface, which has tools ,sub routines and protocols to develop software applications.

What is Restful ?

REpresentational State Transfer (REST) is an architectural style that has a set of constraints and properties based on HTTP(Hyper Text Transfer Protocol)

Rest Constraints :
  • Client Server
  • Stateless
  • Cacheable
  • Uniform Interface


There are few principles bound with REST architectural style:

The principles of REST are 

             Client-Server      - Client sends the request and sever sends the response

            Uniform Interface - defines Interface between client and server. here each                                                            resource  is identified by URI (Uniform Resource Identifier)

           Stateless             - Communication between client and server should be stateless

          Cacheable           - Used to avoid unnecessary call backs to the server  for common                                             data required at the client over and over again


WEB API is a concept not a technology.web api is cross platform can be used in other technologies like java. for example twitter api allows us query and read tweets from our  twitter account and does not dictate any architectural style to create services.


Following are the terms and frequently used in web api programming

  • Resources and URIs
  • HTTP Methods
  • HTTP Status Codes
  • HTTP Content
  • Internet Media Types
  • JSON & XML

HTTP : Hyper Text Transfer Protocol is stateless protocol.Which does not maintain any state between client and server communication and treats every request as new.

URI : Uniform Resource Identifier is a string of characters used to identify the resource on internet using name or location.

URI is used to identify resources, For example, In real world assume there is a person named “X” who lives in “AL SHALI BUILDING,FLOOR 6,DOOR NO 201,Dubai”. We can find that person by name or by address or by both.

URI can be categorized into 2 as URL and URN

URL: Uniform Resource Locator

URN: Uniform Resource Name

URI is used to identify the resource on the internet.It can be done by both URN and URL, but using URN is not sufficient because there can be many resources with  the same name. Most commonly used method is URL and it consists of two required components; The Protocol & The Domain.

Example : 

http://www.dotnetcodetree.blogspot.com/


HTTP Methods :

Web api primarily works based on HTTP Verbs (GET/POST/PUT/DELETE)

HTTP Status Codes :

1XX Codes: Informational codes. Rarely used in modern web apps.
2XX Codes: Success codes. Tells the client that the request succeeded.
3XX Codes: Redirect codes. Tells the client that they may need to redirect to another location.
4XX Codes: Client Error codes. Tells the client that something was wrong with what it sent to the server.
5XX Codes: Server Error codes. Tells the client that something went wrong on the server's side, so that the client may attempt the request again, possibly at a later time.

MIME Types : A media type is a two-part identifier for file formats and format contents transmitted on the Internet.

application/javascript

application/json

application/xml

application/zip

application/pdf

multipart/form-data
.
.
.
.


HTTP Content : HTTP Request and response contains the header content which specifies the message formats and other things.


//Client request
GET /webpage1.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.dotnetcodetree.blogspot.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection:Keep-Alive

//Server Response
HTTP/1.1 200 OK
Date: Sun, 01 April 2018 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Mon, 12 Feb 2017 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed

Internet Media Types: MIME types are used to identity the type of the file. Internet media type is  a backbone of identifying the content types on the internet.



JSON & XML :

XML stands for EXtensible Markup Language.Generally used to transport data over internet for communication between distributed applications.

Example :    

             <Employees>
<Employee>
<Name>Syed</Name>
<Role>Developer</Role>
</Employee>
<Employee>
<Name>Ashish Kumar Panda</Name>
<Role>Developer</Role>
</Employee>
</Employees>

If we open the xml file in the browser will list data in treeview format.

employees ..
  • employee ..
    • nameSyed
      • roleDeveloper
      • employee ..
        • nameAshish Kumar Panda
          • roleDeveloper


        JSON stands for Javascript Object Notation used to represent data in key value pairs.this is also used to store and transport data.

        Example :       {"Name":"Syed" ,"Gender":"M"}



        In the next blog post we see how to implement web api using  visual studio and .net framework...