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 and open it in Visual Studio Code.
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 server into project.json file and restore the package.
In program.cs file, Add relevant using statement.
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.
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,
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, https://github.com/hansamaligamage/WebAppin.NETCore