.NETCore: Create a web application with a Linux server
Create .NET Core web application
Let's see how to write a web application in .NETCore
Create a new project
dotnet new
code .
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 to our package list
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1"
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 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
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,
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.