Listen to me in http://localhost:5000/ with .NETCore on Ubuntu

In my previous post, We saw how to write a console application in .NETCore. Let’s see how to write a web application in this post.

Create a new project

Create a new project

Create a new project and open it in Visual Studio Code.

Initiate a WebHost Builder object

Create a WebHostBuilder instance, since we need a server to run our web application, It’s little bit different to a Console application.
We get an error here, Some packages seem to be missing, ok!!! First of all let’s add a server to run our application.

Add Kestrel to our package list

Add Kestrel to our package list

Add Kestrel server into project.json file and restore the package.

Add relevant using statement for kestrel server

In program.cs file, Add relevant using statement.

run WebHostBuilder

When initiating a WebHostBuilder, It turns your console application into a web application.

Now, Ask the host to build using Build method, and run the webhost. When hit on Run method, It’s going to give a signal to the host to listen on a port and start accepting http traffic.

Let’s run and see the changes

run web application and see what has happened

When we run our application, It gives an error!!!!
It says we haven’t provided a service to startup the application. It means we haven’t mentioned we want to use Kestrel or not when starting our application. Let’s check how we can start our application with kestrel server,

run web application and see what has happened

In here we asked Kestrel to accept a http request and turn it into a http context. In configure, we accept an Application Builder instance, it’s going to perform some actions in our application.
When hit on app.Run(), It’s going to add a terminal to the http request pipeline. Inside app.Run() method, we pass an http context object kestrel has created.

In the terminal window, It shows Hello World - web .
Then it shows Hosting Environment as production., default hosting environment for a .NETCore application.
Then it shows Content root path of our application,
Our web project listen into http://localhost:5000/ which is default url and the default port of our application.

You can download code sample from here,