Create .NET Core web application

Let's see how to write a web application in .NETCore

Create a new project

Create a new project

dotnet new
 
code .

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

"Microsoft.AspNetCore.Server.Kestrel": "1.0.1"

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 our console application into a web application.

Now, Ask the host to build using Build method, and run the web host. 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

public class Program
 {
 public static void Main(string[] args)
 {
 Console.WriteLine("Hello World - web");
  var host = new WebHostBuilder()
 .UseKestrel()
 .Configure(app =>
 {app.Run(c => c.Response.WriteAsync("Hello"));
 })
 .Build();
 host.Run();
 }
 }

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,

web project listen into http://localhost:5000/ which is default url and the default port of our application.