1. List of template projects

If you create an ASP.NET Core Web Application, there are currently 7 template projects available for us to choose from. From this we can see that there are both familiar MVC, WebAPI, and new Razor Page, as well as a template project that combines the popular Angular and React front-end frameworks. Based on the given template, we can choose the appropriate template to build the project framework according to our own needs. At the same time, we can also implement a development strategy of front-end separation based on the provided template project combined with Angular and React clients.

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_1.png

web application templates

2. Empty template project

Let’s first take a look at the structure of the created Empty template project:

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_2.png

Empty Template Project Structure

It can be seen from the figure that it is mainly composed of the following parts:

  1. Dependencies: Dependencies of organizational projects. From the figure we can see that the dependencies are refined into three categories: Analyzers, NuGet, SDK . Among them, NuGet is a package manager specially designed for .net, which organizes the dependencies installed on NuGet; the SDK is mainly the underlying series dependencies of Microsoft; there are actually several other categories: Projects, Bower, npm . Projects is a direct project dependency; Bower is a package manager designed specifically for the web to organize web front-end dependencies; npm is a package manager designed specifically for javascript to organize javascript related dependencies.
  2. Properties: This contains only the launchSettings.json file, which is used to specify the startup settings of the application.
  3. Wwroot: The root directory, generally used to define static files, such as js, css, html, img, ico, etc.
  4. Program: The program entry, which defines the Main function as the entry function. From this point it can be seen that its essence is the console application.
  5. Startup: The program startup class.

2.1. Launch settings for launchSettings.json

First, the properties configured in the json file can refer to
launchSettings.json

.

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_3.png

2.2. Main function of the entry function

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

The ASP.NET Core application needs to be managed by the Host , which provides the runtime environment and is responsible for starting it. So the Main function is mainly used to initialize the host environment, and the initialization of the host environment needs to use WebHostBuilder . After the initialization is complete, call the Run() method to start the application.

  1. WebHost.CreaateDefaultBuilder(): Create a WebHostBuilder .
  2. UseStartup<Startup>(): Specifies the startup class for dependency injection and middleware registration.
  3. Build(): Returns the initialized IWebHost host.
  4. Run(): Start WebHost.

2.3. Host Builder’s WebHostBuilder

A simple line of code for the above Program completes the configuration and startup of an application. But the succinct code is not necessarily simple. Let’s take a look at the
source code

.

public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

            if (env.IsDevelopment())
            {
                var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                if (appAssembly != null)
                {
                    config.AddUserSecrets(appAssembly, optional: true);
                }
            }

            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseIISIntegration()
        .UseDefaultServiceProvider((context, options) =>
        {
            options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
        });
    return builder;
}

It mainly includes the following parts:

  1. UseKestrel: Use Kestrel as the web server.
  2. UseContentRoot: Specifies the content root (content root) used by the web host, such as Views. The default is the current application root directory.
  3. ConfigureAppConfiguration: Sets the current application configuration. Mainly read the appsettinggs.json configuration file, UserSecrets configured in the development environment, add environment variables and command line parameters.
  4. ConfigureLogging: Read the Logging node in the configuration file and configure the logging system.
  5. UseIISIntegration: Use IISIntegration middleware.
  6. UseDefaultServiceProvider: Sets the default dependency injection container.

2.4. Startup Startup

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

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

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

This class mainly includes two methods:

  1. ConfigureService: Used to rely on service registration.
  2. Configure: Used to specify how the application will respond to every HTTP request. Generally used to register middleware.

It involves the following available services:

  1. IServiceCollection: The configuration collection of each service in the current container, the dependency injection container built into ASP.NET Core.
  2. IApplicationBuilder: The request pipeline used to build the application.
  3. IHostingEnvironment : Provides the current EnvironmentName, WebRootPath, and ContentRoot.

2.5. Startup process

First of all, we need to understand that the .net core web application we created is essentially a stand-alone console application. It can’t directly process Http requests. It needs to provide services through Web Server. By default, the .net core uses the built-in cross-platform Kestrel as a web server (and of course other web servers to choose from, such as WebListener, Http.sys, etc.). The web server requires a hosting environment to host it. For example: IIS on Windows, Windows Services, Apache on Linux, Nginx, or Docker can be used as hosts for Web Server.

The host is responsible for launching our .net core application. For example, IIS has added an AspNetCoreModule module that is responsible for starting and stopping the ASP.NET Core program and listening to the state of the ASP.NET Core program, which restarts when our application crashes unexpectedly.

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_4.png

IIS as the host to start the .net core application

When only the service is exposed on the intranet, you can use Kestrel to process http requests directly. Otherwise, the http request is forwarded by means of a reverse proxy server (IIS, Nginx, Apache, etc.). But in general we recommend using a reverse proxy server to handle http requests, because the reverse proxy server can do some extra processing before Kestrel (for more, see
Introduction to Kestrel web server implementation in ASP.NET Core

).

Http request schematic

Through the above description we introduced the concept of Host and Server. We can simply understand that host is a process used to manage applications, and server is used to expose application services. It can also be understood that host is a layer of packaging for the server.

3. MVC vs Razor Page

ASP.NET MVC is an open source framework for developing web applications based on the Microsoft .NET Framework. Based on the idea of ​​separation of concerns, the application is mainly divided into three parts: Model, View, and Controller. The excellent design of MVC is also continued in ASP.NET Core. Razor exists as a high-level view engine
in
ASP.NET

MVC. Razor provides a new markup semantics that greatly reduces user input and expressiveness. The main feature is the use of the @symbol to write markup.
In ASP.NET Core, Razor is more than just a view engine, it provides a new way of page design – Razor Page. Its main features are:

  1. a file path based routing system;
  2. Razor Page is similar to WebForm, an MVVM architecture that supports two-way binding;
  3. Razor Page conforms to the principle of single responsibility, each page exists independently, and the views and code are closely organized.

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_6.png

MVC and Razor Page template project structure differences

4. MVC vs WebAPI

The essential difference is that ASP.NET MVC is used to create web applications that return views and data; however, the ASP.NET WEB API is used to create a complete HTTP service that returns only data without a view return.

As far as the project structure is concerned, the differences are as follows:

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_7.png

5. Angualr template project

We can use Angular to develop SPA web applications, and the structure is much more than the MVC, the main more ClientApp folder. Its code structure is shown below:

ASP.NET_Core__basic_series(1)_Start_with_the_official_template_8.png

Angular Template Project

6. Finally

The introduction of the template project is briefly introduced here, and we will continue to explore it in depth with the practical application!

Orignal link:https://www.jianshu.com/p/0b2f4a6011f1