Introduction To ASP.NET Web API

Overview - In this article, you will see,

  • What is ASP.NET Web API
  • What are RESTful Services
  • Difference between WCF and Web API
  • Creating a Web API Project
What is ASP.NET Web API?

The term API stands for Application Programming Interface. ASP.NET Web API is a framework for building Web APIs, i.e. HTTP based services on top of .NET Framework.

The most common case of using Web API is building RESTful services. These services can then be consumed by a broad range of clients like,
  • Browsers
  • Mobile Applications 
  • Desktop Applications 
  • IOT’s.
One important thing is that though ASP.NET WebAPI framework is widely used for RESTful services, it can also be used to create services that are not RESTful. In short, ASP.NET web API framework does not dictate any specific architecture style for creating services. In this article, we will create RESTful services.

What are RESTful Services?

REST stands for Representational State Transfer. It was first introduced in 2001. REST is an architectural pattern for creating an API that uses HTTP as a communication method. The REST architectural pattern specifies a set of constraints that a system should adhere to.

Now, let’s look at REST Constraints.
  • Client Server
    This is the first constraint. Client sends a request and a Server sends a response. This separation of concerns supports the independence and evolution of client-side logic and server-side logic. 

  • Stateless
    The communication between client and a server must be stateless. 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 is treated independently by the server.

  • Cacheable
    Some data provided by the server like list of products or list of departments as this data is does not change the fact  that often this constraint says  how long data is good for so that the client does not have to come back to the server for the same data over and over again. Caching avoids unnecessary processing and significantly increases the performance of the system.

  • Uniform Interface
    Uniform interface determines the interface between client and the server. To understand uniform interface we first need to understand what a resource is and the HTTP verbs like GET, PUT, POST and DELETE. In the context of REST API, resources typically represent data entities like product, employees etc. which are all resource.s The HTTP verb sends a request to API and tells it what to do with that resource. The resource is identified by a specific URI (Uniform Resource Identifier)
For example
  • /Employees the verb is GET here it is going to get list of employees 
  • /Employees/1 the verb is GET going to fetch employee where id is 1
  • /Employees if the verb is POST going to create a new employee
  • /Employee/1 if the verb is PUT going to update that employee details where id is 1
  • /Employee/1 if the verb is DELETE going to delete that record where id is 1 .
 Another concept related to Uniform Interface we need to understand is that here is HATOES.

HATOES stands for Hypermedia as the Engine of Application State.

It means that in each request there will be a set of Hyperlinks that lets you know what other actions can be performed  on the resource. We will see this in our later articles.
  
Difference Between WCF and Web API?

WCF stands for Windows Communication Foundation and we can use WCF also for creating RESTful services. The problem with WCF is that a lot of configuration is required to turn a WCF service into a RESTful service. The more flexible choice for creating RESTful service is ASP.NET Web API which is specifically created for this purpose. 

When should we use WCF over ASP.NET Web API?

WCF is more suited for building services that are transport or protocol independent.

For example,

You want to build a single service that can be consumed by two different clients. Let’s say a JAVA client and a .net client. Java client wants a transport protocol to be HTTP and message format to be XML for interoperability. Whereas, the .NET client wants the protocol to be TCP and the message format should be binary, for this scenario WCF is very useful. We create a simple WCF service and configure to endpoints one for each client one for Java and the other for .NET.

There is nothing wrong in using WCF service as RESTful service but it’s time consuming because configuration can be a real headache.

If you are limited to .NET framework 3.5, then you can use WCF service. If you have other frameworks, then you can use Web API for creating RESTful services.

Now, let’s create a sample Web API project for this we will use Visual Studio 2015
In this part we will see-
  • creating a new ASP.NET Web API project
  • Explore and Understand the WebAPI Code auto-generated by Visual Studio.
To create a new ASP.NET Web APi Project click on File->New->Project as,

ASP . NET

In project Dialog box select visual C# select web application as,

ASP . NET

On the next subsequent screen, you will get plenty of options like create empty project, MVC, web API and so on. So click on Web API and click Ok.

ASP . NET

When you click ok it will take a few minutes to create a sample web API Project.

Note - If you get an error as Package Installation error (Could not add on required packages in the project) OR Failed to initialize PowerShell host, just launch windows PowerShell. To launch windows PowerShell, click on start searching for windows PowerShell as.

ASP . NET

Right click on the windows PowerShell and run as administrator you will get a prompt.

ASP . NET

You need to set a policy for all signed users just type as SET execution policy all signed and hit enter,

ASP . NET

When you hit enter if you don’t get any error that means you had executed that command successfully.

command successfully

Now, launch Visual Studio and go to Package Manager Console.

command successfully

When you click on that, it will open a package manager console at the bottom.

command successfully

If you get a security prompt, press R and enter and refresh the API application. So, this would create API project successfully.
Now, let’s explore the code that is auto-generated by VS. If you have worked with ASP.NET MVC before, this folder structure should be familiar to you.

folder structure

We have got folders for Models, Views, and Controllers. Within the Controllers folder, we have got both, MVC Controller and Web API Controller.

folder structure

Here, Web API Controllers are different from MVC Controllers . The ValuesController is ASP.NET WebAPI Controller.

ASP.NET WebAPI

Notice, that the ValuesController Class inherits from ApiController Class which is present in sytem.web.http namespace which is included in that file automatically.

The Home Controller is an MVC Controller,

ASP.NET WebAPI  

Which inherits from Controller class and which is present in system.web.mvc namespace.

Now, in ValuesController class, we have values like GET, POST, PUT and DELETE,
system.web.mvc

These methods responds to HTTP verbs. We have two overloaded versions of GET method one is without parameter and one with parameter as id,

system.web.mvc

These methods respond to HTTP verbs depending upon whether the value for id is specified in the URI or not. Now let's look at the default route in our application in our global.asax file we have,

system.web.mvc

So in global.asax we have application start event handler method. This event is raised when an application starts. We have configurations for filters, bundles etc . The one we are looking for is configuration in Web API. The configuration is present in Register method of web API in config class so right click on Register and click go to definition as,


Which is going to take us to Register method of webconfig class. This class webconfig class is present in App_Start folder as,

system.web.mvc

In our webconfig file we have default route mapped. Web API routes are different from MVC routes.

MVC routes are present in RouteConfig.cs.

In webconfig file the default route is,
system.web.mvc

It starts with the word API and then the name of the controller and then the optional ID parameter.

Now let’s run our project which will take us to default start page as,

default start page

Now in the URL we will type api/values; as in our default route, the first is api and second is controller name as the api controller name is values as:

default start page

Now here when you hit enter it processes a GET request. Now which GET method is getting responded to?  We don’t have any idea, as we are not passing any value to this URI that means the first overloaded version of GET without a parameter is being called. Now just hit and enter and let’s see what we get:

default start page

We had got an authorization error this is because of the authorize attribute in Valuescontroller.cs file as,

Valuescontroller

Which is related to security . We will see this in upcoming articles, for now just comment build the solution.

Valuescontroller
Now if you see the code what is GET method returning? It's returning two strings --  Value 1 and Value 2.

We have another overloaded version of GET parameter that takes ID parameter. In the default route of webAPI the id parameter is optional, that’s why we are able to call the GET method without specifying the ID parameter.

Now if we specify id in the URL,

specify id in the URL
We get string value as expected -- that means the second overloaded function of GET method is called where value is specified with a parameter as id,

overloaded function
Now, comment the entire code of ValuesController.cs and load the page we get as,

controller
We have commented the Values Controller code and we get an error that says it was searching for name Values as controller but didn’t find any.

Conclusion

So, this was about ASP.NET Web API and creating a sample project. Hope this article was helpful.

Up Next
    Ebook Download
    View all
    Learn
    View all