Explain the project structure change of dotnet core in simple terms

Time:2021-9-4

Sometimes, the more basic things, the more people don’t understand.

A few days ago, I reviewed the code of a project and found very basic content. Some people will make mistakes in understanding it.

Today, based on this point, write about the main types of project structure, transformation and evolution of dotnet core.

1、 The most basic application console

Console application is the most basic project in dotnet core and even the front dotnet framework.

Let’s create a console project to see:

% dotnet new console -o demo

When the creation is complete, open the project. There is only one file in the projectProgram.cs, there’s only one wayMain

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

In all types of projects at dotnet core,Program.csAre the first entrances,mainMethod is also the initial entry method.

In this project, there is another document that needs to be understood,demo.csproj, this is the definition file of this project:

Exe
    net5.0

Inside,OutputTypeTell the editor that the project can be executed directly after compilation,TargetFrameworkDefine the framework in which to run.

Note that this frame string has a cross reference table:net5.0Corresponding to.Net 5.0; If you want to useDotnet Core 3.1, the corresponding string isnetcoreapp3.1, notnet3.1。 To be exact, 3.1 is.Net Core 3.1, and 5.0 is.Net 5.0。 Don’t worry too much. It’s just Microsoft’s naming rules.

    In order to prevent not providing the reprint of the original website, the original link is added here:https://www.cnblogs.com/tiger-wang/p/14267942.html

This is the initial state of the console application console.

Next, let’s take a look at how this project is transformed into a web application.

2、 Convert to web application

First, we need to changedemo.csprojProject definition file.

Web application running inWebHostAbove, not from direct execution. So we need toOutputTypeItem removed.

In addition, the SDK also needs to be changed. Console we useMicrosoft.NET.Sdk, the web application should be changed toMicrosoft.NET.Sdk.Web

net5.0

Save after modification.

At this time, it should be noted that the of the project has changed:

  • Dependent framework fromMicrosoft.NETCore.AppTwo, one moreMicrosoft.AspNetCore.App, indicating that now this is aAsp.net CoreApplication of;
  • A directory is automatically generated in the projectProperties, there is one more file belowlaunchSettings.json。 This document should be familiar to everyone, so I won’t explain it.

At this time, the application has been transferred from console to web application.

The ASP. Net core framework provides a host for web loading. What we need to do is add the host builder to the program. Typically, we need two Builders:

  • Generic host builder
  • Web host builder

1. Configure general host

General purpose host inMicrosoft.Extensions.Hosting.HostIn, it mainly provides the following functions for web applications:

  • Dependency injection
  • journal
  • Configure iconfiguration
  • Ihostedservice implementation

It’s easy to join a general host. There’s only one wayCreateDefaultBuilder

class Program
{
    static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .Build()
            .Run();
    }
}

2. Configure web host

The web host is the real web related content, which mainly realizes:

  • HTTP support
  • Set kestrol server as web server
  • Add IIS support

Joining a web host is also a methodConfigureWebHostDefaults

class Program
{
    static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
            })
            .Build()
            .Run();
    }
}

This method is used to add the HTTP request pipeline and inject the services we need. Injecting the services we need is the most commonStartup.csContent of the.

Next, let’s createStartup.cs

namespace demo
{
    public class Startup
    {
    }
}

In frontConfigureWebHostDefaultsIn, joinStartup, and supplement the code:

class Program
{
    static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            })
            .Build()
            .Run();
    }
}

This is it.Program.csThe complete code in. Tidy it up, which is what we usually look like:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            });
}

But it doesn’t work here becauseStartup.csIt’s still empty.

3. Supplement startup class

StartupClass plays an important role in asp.net core application. This class is used to:

  • Injecting services using Di containers
  • Set the HTTP request pipeline to plug into the middleware

Let’s supplement the required methods below:

namespace demo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        }
    }
}

Run, here, the web application can start normally.

4. Add a route to the application

The web application started, but there was nothing in it. It was empty.

To access any resource in the web application, you need to configure routing. The routing here is basically the mapping between incoming HTTP requests and resources.

We can use the following middleware to start Routing:

  • UseRouting
  • UseEndpoints

Give it a try:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseEndpoints(endpoint => {
        endpoint.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello from Demo");
        });
    });
}

This time, you will see the correct output in the browser.

We can useMapGetMap more resources:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseEndpoints(endpoint =>
    {
        endpoint.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello from Demo");
        });
        endpoint.MapGet("/test", async context =>
        {
            await context.Response.WriteAsync("Hello from Demo.Test");
        });
        endpoint.MapGet("/about", async context =>
        {
            await context.Response.WriteAsync("Hello from Demo.About");
        });
    });
}

Here, we have successfully transformed the console application into a web application.

3、 Extended content

The web application completed above is the foundation of web application. Based on this content, we can also extend to other project structures.

1. Change to MVC application

Need inConfigureServices Medium injectionAddControllersWithViews, and inConfigureAdd inMapDefaultControllerRoute

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseEndpoints(endpoint =>
        {
            endpoint.MapDefaultControllerRoute();
        });
    }
}

2. Change to webapi application

Need injectionAddControllersandMapControllers

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseEndpoints(endpoint =>
        {
            endpoint.MapControllers();
        });
    }
}

3. Change to razor application

Need injectionAddRazorPagesandMapRazorPages

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseEndpoints(endpoint =>
        {
            endpoint.MapRazorPages();
        });
    }
}

4、 Summary

It seems that the process is actually very simple. In this way, you can further understand the project structure and application operation process of dotnet core.

I hope it can help you.

The supporting code of this article is:https://github.com/humornif/Demo-Code/tree/master/0038/demo

WeChat official account: Lao Wang Plus

Scanning the two-dimensional code, paying attention to the official account, can get the latest personal articles and content push.

The copyright of this article belongs to the author. Please keep this statement and the link to the original text