ASP.Net Web API Core from “Vanilla” Project Template — Part I
ASP.Net Web API Core from “Vanilla” Project Template — Part I
In this first installment in a series of articles on ASP.NET Core, learn the first steps in the process of creating an ASP.NET Core for the web.
Join the DZone community and get the full member experience.Join For Free
What I would like to focus on this series of writings is how to create a simple HTTP API that covers main HTTP verbs such as HTTP GET, POST, PUT, DELETE, AND PATCH using ASP.NET Core.
In light of the sheer amount of information that needs to be covered, I have segmented the full topic into multiple articles.
As a use case to learn the technology, we would create an English vocabulary sample application which contains English vocabularies, its definitions, as well as how sentences can be formed with those vocabularies.
However, it all starts with an “Empty” project template instead of using the “Web API” project template, because I believe that in order to better understand how the underlying technology works under the hood, we should start with the most fundamental bits and create and improve the bits from there.
I also believe that to better understand how the underlying technology works can lead to faster debugging, and also allows the developers to more elegant improvements.
All the projects and code which are shown in the article are created using some tools and frameworks which are defined in the Prerequisites section.
- Visual Studio 2015
- .Net Core
Click here to find a complete set of information on how to install all required bits to start creating ASP.NET Core API.
Create HTTP API
1. Create a New and Empty ASP.NET Core Project
Create a new ASP.NET Core project from Visual Studio 2015. When you are presented with the following screenshot, highlight “.NET Core” on the left pane, and choose “ASP.NET Core Web Application (.NET Core)” on the right pane.
Subsequently, when the developer is presented with the following screenshot, the developer should choose “Empty” project.
One thing to note, even though the “Empty” project template is chosen, which is the most vanilla project template available in VS 2015, the IDE will still auto-generate a couple of file dependencies for developers to start with, as shown in the following screenshot.
2. Default Web Server in ASP.NET Core
Before we drill down into the analysis of Program.cs and Startup.cs files, which are the two files created automatically when creating an ASP.NET Core project, let us talk a little bit about the default web server which is used in ASP.NET Core.
By default, ASP.NET Core is using the Kestrel web server, which is the open-source and cross-platform web server based on libuv. Libuv instead, is a multi-platform support library which focuses on async I/O. The detailed implementation of Kestrel web server and libuv library can be found here or here.
ASP.NET Core applications can work without integration with IIS or IIS Express. However, it definitely needs a web server, which is Kestrel in this case.
In development, it is fine to write and test ASP.NET Core applications with Kestrel even if it doesn't have an IIS integration. However, in Production, it is almost certain that IIS or another reverse proxy server such as Apache, or Nginx is required. Reason being, a reverse proxy server provides a lot of important features which are not supported by the Kestrel web server. Some of the main features included are: Port 80/443 forwarding via host headers, Process lifetime management, Certificate management, Static file serving and gzip compression, URL Rewriting. The fundamentals of how ASP.NET Core application works with Kestrel can be found at here. Additionally, the fundamentals of how ASP.NET Core applications work with Kestrel and integration with IIS can be found here.
Also, this article is very useful too for understanding how IIS can be set up as a reverse proxy for ASP.NET Core applications and the Kestrel web server.
3. Analysis of Program.cs and Startup.cs
After we create the ASP.NET Core web app with an Empty project template and run the application by clicking on the “IIS Express” in VS 2015, we will see a page displayed on the browser that displays “Hello World!’ on the page.
When we run the application, the following methods in two main files, Program.cs and Startup.cs, are executed in sequence.
1. public static void Main(string args) - Program.cs 2. public void ConfigureServices(IServiceCollection services)– Program.cs 3. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) - Startup.cs
THE “Hello World!” message which is returned to the browser page is from the following code execution.
Let’s take a look at the public static void Main(string args) of Program.cs.
There are many articles that developers can refer to understand what those function calls are and I would not repeat those here. And there are three function calls (UseKestrel, UseIISIntegration and UseStartup<T>) which are important and self-explanatory too.
4. Create First HTTP GET Method with ASP.NET Core
There are a few steps involved in creating the first HTTP GET API. But before we do that, let’s comment out some of the default generated code provided by VS 2015.
Comment out the app.Run() method call as shown in the following screenshot in Configure method.
General Steps to Create the First HTTP GET API.
a. Add the MVC Services in ConfigureServices method (Startup.cs).
b. Add the MVC middleware to the request pipeline Configure in method (Startup.cs).
c. Create a model class to represent the data to return to HTTP API client.
d. Create a controller class with at least one public method.
e. Set the routing so that client knows how to access the API with the correct URL.
f. Test the HTTP API with Postman.
a. Add the MVC Services in ConfigureServices Method (Startup.cs).
Add the first line of code, services.AddMvc(); in ConfigureServices method. However, we can see a squiggly line under AddMvc() method.
If we mouse over to the method, in VS 2015, it shows a lightbulb icon with an informational message of what is lacking in order to call the AddMvc()method.
Click on the “Add package Microsoft.AspNetCore.Mvc 1.1.1” which is highlighted in yellowish color and VS 2015 is smart enough to add the missing nugget package, which in this case is Microsoft.AspNetCore.Mvc 1.1.1.
b. Add the MVC Services in Configure Method (Startup.cs).
Add the app.UseMvc(); in Configure method as shown in the following screenshot.
c. Create a Model Class to Represent the Data to Return to HTTP API Client.
Before we create the first Model class, it would be great to a folder that stores all the model classes in it.
Create a model class, EnglishVocabModel, and EnglishVocabSentenceModel, to represent the data to return to HTTP API client.
Finally, create a data store simulator to return all hard-coded model data to the controller.
d. Create a Controller Class with at Least One Public Method.
Before we create the first controller class, it would be great to make a folder that stores all the controller classes in it.
Then, create a vanilla controller class in the above folder and the code should look like following.
Controller class resides in Microsoft.AspNetCore.Mvc namespace, so you need to make sure that the following line is included in the namespace definition.
After that, create a method, GetEnglishVocabs(), as shown in the following screenshot.
However, if we run the application, and test it with any HTTP Client, in this case, we use Postman, it would not work. Reason being, there is no information on Routing which is one of the important mechanism in the ASP.NET Core web.
e. Set the Routing So That the Client Knows How to Access the API with the Correct URL
Before we talk about how to define routing in the ASP.NET Core web, we need to know that there are two routing implementations in ASP.NET Core web: conventional-based routing and attribute-based routing.
In conventional-based routing, we have to include the routing information in the app.UseMvc(); method in Startup.cs. The following screenshot shows how it can be done.
However, in this article, we are focusing on how to use attribute-based routing instead, because it is more precise and clearer to use in an HTTP Web API type of system.
So, we first need to define the [Route(“api/englishvocabs”)] attribute on top of the controller class, followed by [HttpGet()] attribute at the method level, as shown in the following screenshot.
With this setting, when we access the URL from any HTTP client, we have to combine the host URL, concatenate it with the relative URL defined in Route attribute, and finally, concatenate it with the one defined in HttpGet() attribute if there are any.
f. Test the HTTP API with Postman
Now, run the application by pressing the “IIS Express” drop-down button in VS 2015 to run the ASP.NET Core Web API application, and test it with Postman as shown in the following screenshot. If it works successfully, it should return all the English vocabularies and its definition and sentences which we have hard-coded in code.
Take note that the port number shown in the screenshot may not be the same for each developer and it verify which port to use in the IIS Express which is running.
This is just the beginning of a series of writings on ASP.NET Core Web API. Stay tuned!
Opinions expressed by DZone contributors are their own.