Lets get hands dirty
First things first, you need to have the .NET SDK installed on your machine to be able to start creating application in C# and ASP.NET Core. You could download the latest version matching your host environment in here, at the time of writing this post .NET 9.0 is the latest version.
Now, open terminal and run
dotnet new console --name TryWebWithFun
This will create a simple empty console application with two important files, Program.cs
where we will write our application and it acts an entry point, TryWebWithFun.csproj
which holds the configurations for the project. Open the latter and change the first line to point to the Web
SDK:
<Project Sdk="Microsoft.NET.Sdk.Web">`
<!-- Omitted for berevity of the code -->
</Project>
Great! In .NET, we have the concept of a Host, it could be generic or specific for a purpose; the Host is responsible for startup of the application and its lifetime management.
A host is an object that encapsulates an app's resources and lifetime functionality, such as, dependency injection, logging, configuration, application shutdown, and IHostedService implementations
You could follow up for more details in here, but for now, let's create one for our example to host a web application:
var builder = WebApplication.CreateBuilder();
var app = var app = builder.Build();
we could configure all the above-mentioned points using the builder
instance and then configuring the application specific pipelines using the app
instance.
To configure our application we need to register an endpoint, that is possible using fluent api provided with the app instance:
app.MapGet("hello" , () => "world");
This creates a HTTP endpoint with the path hello
, and it returns a simple string.
Finally to run our application either call the app.Run()
or await app.RunAsync();
and go to the terminal and the folder your .csproj
file is in and run
dotnet run
That's it 😉
To specify ports and URL either pass them to the Run
method, or pass them as an argument to the dotnet run
command.
PS: Depending on your terminal of choice you might need to pass it differently to the command line.
Of course one could enrich the endpoints and the configuration of the application with more sophisticated settings; for instance, adding authorization, or logging and dependency injection.
Thanks for reading so far, enjoy coding and Dametoon Garm [1] 😊