Creating ASP.NET Web API Application

Creating ASP.NET Web API Application using Visual Studio

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.

  1. How to Create an ASP.NET Web API application using Visual Studio?
  2. Understanding the Folder structure and Auto-Generated Code in Web API Application.
  3. Understanding the Web API Controller.
  4. What is GET, POST, PUT and DELETE HTTP Verbs in Web API?
  5. Understanding the WebApiConfig in ASP.NET Web API Application.
  6. Understanding the Request Verbs, Request Header, Request Body, and Response Body.
Creating ASP.NET Web API Application using Visual Studio:

First, open the Visual Studio and then select File => New Project as shown in the below image.

Creating Web API Application step by step

In the New Project” window Select “Visual C#” under theInstalled – Templatesand From the middle pane select the ASP.NET Web Application and name the project asFirstWebAPIDemo” and then click on theOKbutton as shown in the below image.

Creating Web API Application - Selecting Project Template

Once you click on the OK button, then a new window will open with the Name New ASP.NET Project for selecting project Templates, and from that window select the Web API project template and click on the OK button as shown in the below image.

Creating Web API Application - Selecting Web API Template

Once you click on the OK button, It will take some time to create the project for us.

Understanding the Folder Structure of Web API Application:

If you have worked with ASP.NET MVC Framework, then the project folder structure should be familiar to you as shown below. 

Creating Web API Application - Web API Project Structure

Here, we have separate folders for Models, Views, and Controllers and moreover, within the Controllers folder, we have both MVC as well as Web API Controller as shown in the below image.

Creating Web API Application - Controller

The important thing to keep in mind is that the Web API Controllers are different from MVC Controllers. In our example, the ValuesController is WebAPI Controller.

Creating Web API Application - Web API Controller

If you observe the above ValuesController Class, then you will see that it inherits from the ApiController class which is present in sytem.web.http namespace.

Further, if you notice that the HomeController class is an MVC Controller, which is inherited from the Controller class that is present in System.Web.Mvc namespace is shown in the below image.

Creating Web API Application - MVC Controller

Here we are going to focus on the Web API controller (i.e. Values Controller).

Notice that in the ValuesController we have methods such as Get, Put, Post, and Delete that map to the HTTP verbs GET, PUT, POST, and DELETE respectively as shown in the below image. 

Creating Web API Application - Action Methods of values controller

We have 2 overloaded versions of the Get() method – One method without any parameters and the other one with the id parameter. Both of these methods respond to the GET HTTP verb depending on whether the id parameter is passed or not in the URL.

Now let’s look at the default route for our Web API project. We have the Application_Start() method within the Global.asax file. This method is executed when the application starts for the first time and it is also going to be executed only once. In the Application_Start() method we have the configuration for Filters, Bundles, etc. as shown below. 

Creating Web API Application - Application Start Event

Here, we are only interested in WebApiConfig.Register() method. So right-click on the WebApiConfig.Register method and then select the “Go To Definition” from the context menu which will take you to the Register() method of the WebApiConfig class as shown below. 

Creating Web API Application - Web API Config File

This class is in the App_Start folder.

You can see a default route is configured within the Register() method for our Web API project. The Web API routes are different from the MVC routes. You can find the MVC routes in RouteConfig.cs file which is present in the App_Start folder.

The default route in Web API starts with the word API followed by a / and then the name of the controller and then another / and an optional id parameter as shown below.

“api/{controller}/{id}”

At this point, if you use the following URI in the browser, you will get an error stating – Authorization has been denied for this request.

http://localhost:xxxxx/api/values

To get rid of this error, comment Authorize attribute on the ValuesController class. This is related to security which we will discuss in a later article.

Now if you issue the URI http://localhost:xxxxx/api/values in the browser, then you should see the following XML as the result

Creating Web API Application - Web API Response

Let us understand what is going on here.

The name of the controller is “values“. So if you issue a URI http://localhost:portnumber/api/values, then the Web API Framework is going to look for a controller with the name Values + the word controller i.e. ValuesController in your application.

So if you have specified values in the URI it is going to look for ValuesController, if you specify Products, then it is going to look for ProductsController

In a real-world application, this might be the domain name, for example, http://dotnettutorials.net/api/values The browser is issuing a GET request which maps to the Get() method in the ValuesController class. The GET() in the values controller is returning value1 and value2 which is what we see in the browser.

We have another overload of GET() method within the Values Controller which takes the Id parameter. If you remember with the default route within the WebApiConfig file, we specified the id parameter as optional. This is the reason why we are able to call the GET method with or without the Id parameter. So, if you specified the id parameter in the URI, then, the Get() method with the id parameter in the values controller is going to be called 

If a controller with the specified name is not found by the Web API Framework, then the Framework will have an error. For example, in our application, if we comment “ValuesController” class in our project and then use the URI /api/values then you will get the following error

No HTTP resource was found that matches the request URI ‘http://localhost:15648/api/values’. No type was found that matches the controller named ‘values’.

Let’s discuss POST, PUT and DELETE.

In a database table row, we can perform the following 4 actions

Creating Web API Application - CRUD Operations

From the ASP.NET Web API point of view, these 4 actions correspond to GET, POST, PUT and DELETE verbs as shown below 

Creating Web API Application - HTTP Verbs

Let us discuss some terms and concepts which are related to HTTP requests and responses.
Request Verbs: 

The HTTP verbs such as GET, POST, PUT, and DELETE describe what should be done with the Web API resource. For example, do you need to read, create, update or delete an entity? The HTTP Verbs GET, PUT, POST, and DELETE are the most commonly used verbs in real-time applications. For the list of the complete  HTTP verbs, please check the following URL

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Request Header: 

When a client sends the request to the server, the request contains a header and a body. The header of the request contains some additional information such as what type of response the client required. For example, the client wants the response to be in XML or JSON format.

Request Body: 

The Request Body contains the data that you want to send to the server. For example, a POST request contains the data in the Request Body for the new item that you want to create. The data may be in the form of XML or JSON.

Response Body: 

The Response Body contains the data that is sent as a response from the server. For example, if you request a specific employee, then the response body includes the employee details either in the form of XML or JSON.

Response Status codes: 

The Response Status Codes are the HTTP status codes that will specify the status of the request. The most common status codes are 200/OK, 204/No Content, 500/Internal Server Error, and 404/Not Found. If you want to see the complete list of HTTP status codes then please follow the below

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

To perform the GET, POST, PUT & DELETE actions, we will use a tool called Fiddler. You can download fiddler from the following link

https://www.telerik.com/download/fiddler

Modify the ValuesController as shown below, so that it can support POST, PUT and DELETE actions.
public class ValuesController : ApiController
{
    static List<string> strings = new List<string>()
    {
        "value0", "value1", "value2"
    };
    // GET api/values
    public IEnumerable<string> Get()
    {
        return strings;
    }

    // GET api/values/5
    public string Get(int id)
    {
        return strings[id];
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
        strings.Add(value);
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
        strings[id] = value;
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
        strings.RemoveAt(id);
    }
}

At the moment the Post(), Put() and Delete() methods in the ValuesController are returning void. That is the reason why we are getting the status code 204 No Content. In ASP.NET Web API, an action method that returns void will send the status code 204 No Content by default, but we can control this behavior which we will discuss in a later article. 

In the next article, I am going to discuss how to use Swagger in WEB API to document and test ASP.NET Web API services. Here, in this article, I try to explain creating an ASP.NET Web API application with an example. I hope you enjoy this How to Create ASP.NET Web API Application article.

9 thoughts on “Creating ASP.NET Web API Application”

  1. Hello and thank you for this wonderful tutorial! I have a question about web API. I understood the main idea of the web api but I did not understand how an end-user can use it. Let’s assume that you’ve entered an id number to the URL to get the value but for an end-user it is not practical to use it. How can we convert it to a graphical user interface? Or how can we use web api in a real application? On the internet it is written that web api is used to build applications that can be used in many platforms such as phone, tablet or pc but most of the informations are just for testing it. Could you please explain it? Thanks in advance!

  2. Mete,
    Here in back-end, We are just working on how the asked resource will be provided to client.
    Client could be any platform Android app, IOS app, Web application, IOT device etc, Which will have the URL to query for example :
    to get list of product: client will call “https://www.abc.com/api/Products” this will gives you a JSON object which will be consumed by any client mentioned above using Angular, React, Vue.Js , ajax etc, then it will be shown to end user in graphical representation.

  3. I have implemented token based authentication by following this tutorial. But mobile team saying that this is not a valid token format. Dot (.) is not present in this token.

Leave a Reply

Your email address will not be published. Required fields are marked *