ASP.NET Tutorial - Hello World in 10 minutes

September 17, 2020

In the command prompt, run the following commands:

dotnet new webApp -o myWebApp --no-https
cd myWebApp

What do these commands mean? The dotnet new command creates a new application.

  • The webApp parameter selects what template to use when creating your app.
  • The -o parameter creates a directory named myWebApp where your app is stored.
  • The --no-https flag specifies not to enable HTTPS.
  • The cd myWebApp command puts you into the newly created app directory.

What files were created? Several files were created in the myWebApp directory, to give you a simple web application that is ready to run.

  • Startup.cs contains all the settings and configurations
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace myWebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
  • The myWebApp/Pages directory contains some example web pages for the application.

Example: index.html

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1>Hello, world!</h1>
    <p>The time on the server is @DateTime.Now</p>
</div>
  • myWebApp.csproj defines what libraries are referenced etc.
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>