ASP.NET Core 3.0 Getting Started

Course Description

  • Some changes have occurred, compared with 2.x, project structure, Blazor, SignalR, gRPC etc.
  • Video is expected structure
    • ASP.NET Core 3.0 Project Architecture Overview
    • ASP.NET Core MVC Profile
    • BLAZE
    • SignalR
    • web API
    • gRPC
    • release

A. Create a project

  • It is a console application on dotnet core nature

DI dependency injection (Dependency Injection)

  • IoC container (Inversion of Control) control inversion
    • Registration (Service)
    • Request examples
    • Examples of life cycle
  • The life cycle
    • Transient (in every request generates a new instance, the shortest)
    • Scoped (one example of a Web request is generated, long)
    • Singleton (from start to stop the application, created only once, longest)

1. ConfigureServices

services.AddControllersWithViews();
services.AddControllers();
// 别的类每次请求 IClock 这个接口时,都会返回一个 ChinaClock 类的实例
// services.AddSingleton<IClock, ChinaClock>();
services.AddSingleton<IClock, UtcClock>();

When it is desired to change the interface implementation class when only need to modify the dependency injection.

public class HomeController: Controller
{   // 不需要更改
    public HomeController(IClock clock)
    {
    
    }
}
1.1 DI benefits
  • Decoupling, there is no strong dependence.
    • Conducive to unit test
  • Not need to know the specific class of service
  • You do not need to manage the life cycle of service class

2. Configure

  • For HTTP requests, build pipeline
2.1 ASP.NET Core pipeline (pipeline)
  • Something in the pipeline processing request (request for data, or some thing for Web Server), is called middleware
  • Auth authentication, MVC framework, Static Files Static files (HTML, JS, CSS)
2.2 Middleware registered (order is important)
// 在开发环境中,一些没有被处理或者捕获的异常就会传到这里,展示成一个页面
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

// 不使用这个中间件就无法访问静态文件(HTML,JS,CSS)
// 它可以放在 UesRouting 前,因为不需要知道路由信息
app.UseStaticFiles();

// 将 HTTP 请求转换为 HTTPS 请求,强制用户使用 TLS 协议(SLL)
app.UseHttpsRedirection();

// 身份认证,必须放在 UseEndpoints 前面,因为在使用 MVC 等之前就应该完成身份认证
app.UseAuthtication();

// 路由中间件,检查在应用中已经被注册的端点,这些端点有可能是被 MVC 注册的, 也有可能是RazorPages 注册的。
// 会判断这个 HTTP 请求是在哪个端点上出现的,并把这些信息传达给后面需要用到这些信息的中间件。
app.UseRouting();

// 端点中间件,对端点进行注册
app.UseEndpoints(endpoints = >
{
    endpoints.MapGet(pattern:"/", requestDelegate:async context =>
    {
        await context.Response.WriteAsync(text: "Hello World!");
    });
    // MVC
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    // Attribute:类似在Controller上加上[Route("api/[Controller]")]
    // 注意, services.AddControllers(); 和 endpoints.MapControllers(); 方法成对出现,。
    endpoints.MapControllers();
});
2.3 endpoint endpoint
  • Endpoint is the end of the incoming HTTP request URL that part, this branch is processed middleware.

  • /{controller} /{action}
  • /home /index

Why should "routing" separated out from the MVC, with other middleware to use it?

Diversity 2.4 ASP.NET Core applications
  • MVC:/Home /Index
  • Razor Pages:/SomePage
  • SignalR:/Hub /Chat

3. The server comes with Kestrel

  • Visual Studio configures IIS server, but the application itself will ASP.NET Core with a small server Kestrel
3.1 launchSettings.json
  • Set iisSettings, IISExpress server, if you remove the rear profiles of IISExpress, you can put iisSettings here were also deleted

  • configuration profiles, where multiple servers can be configured
    • There IISExpress default server and server Kestrel

4. The method of custom ConfigureDevelopment

// 自定义 ConfigureDevelopment 方法
public void ConfigureDevelopment(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
}

// 如果找不到自定义的 Configure 方法,就会执行默认的
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 通过 IWebHostEnvironment 进行注入
    // 可以是 IsDevelopment(),也可以是 IsProduction(),还可以自定义 IsEnvironment("OK")
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
}

// ConfigureServices()方法也可以自定义配置,还可以对Starup 类进行自定义(例如StartupDevelopment)

5. static files

  • Manually create the wwwroot folder (css, js, image)
  • Use app.UseStaticFiles () middleware can make wwwroot in the static files become accessible (for example: localhost: 5000 / images / logo.png)

II. Package Management

  • Server-side (back-end): Nuget
  • Front-end: Npm
    • 添加 npm Configuration File (package.json)
  • libman.json (right click - Management Client)

1. Combined CSS files, and compress them

  • Establish bundleconfig.json file
[
    // 合并
    {
        "outputFileName":"wwwroot/css/all.min.css",
        "innputFiles":[
            "wwwroot/lib/bootstrap/dist/css/bootstrap.css",
            "wwwroot/css/site.css"
        ]
    },
    
    // 移动 + 压缩
    {
        "outputFileName":"wwwroot/css/bootstrap.css",
        "innputFiles":[
            "wwwroot/lib/bootstrap/dist/css/bootstrap.css"
        ],
        "minify":{
            "enabled":true
        }
    }
]
  • By mounting Nuget BuildBundlerMinifier, then generate

III. Use MVC related technologies

  • Controller
  • Tag Helper
  • Settings
  • View Component
  • Razor Page

1. Tag Helper

  • Add Razor View Imports
  • Global Add Tag Helper
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
  • Tag Helper setting environment
<environmet include="Development">
    <link rel="stylesheet" asp-href-include="css/*" asp-href-exclude="css/all.min.css" />
</environmet>

<environmet exinclude="Development">
    <link rel="stylesheet" asp-href-include="all.min.css" />
</environmet>

<!-- 防止图片被缓存 -->
<img asp-append-version="true" alt="Logo" src="images/logo.png" />

Four. ASP.NET Core configuration information

  • Key-Value key-value pairs
  • Memory, JSON, XML, INI and other documents, or system environment variables
  • Configuration information and configuration system is decoupled
  • Dependency injection can

1. ASP.NET Core configuration information source (sequential search, the front cover behind the same)

  • appsettings.json
    • appsettings.{Environment}.json
  • Secret Manager
  • Environment Variables
  • Command line parameters

appsettings.json

{
    "Three":{
        "Threshold":30
    }
}

Startup:

private readonly IConfiguration _configuration;

public Startup(IConfiguration configuration)
{
    _configuration = configuration;
    // var three = _configuration["Three:Threshold"];
}

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ThreeOptions>(_configuration.GetSection("Three"));
    // ...
}

Controller:

private readonly IOptions<ThreeOptions> _threeOptions;

public HomeController(IOptions<ThreeOptions> threeOptions)
{
    _threeOptions = threeOptions;
}

Razor:

@inject IOptions<ThreeOptions> options
Clear default source
  • Program:
Host.ConfigureAppConfiguration((context, configBuilder) =>
                               {
                                   configBuilder.Sources.Clear();
                                   configBulider.AddJsonFile("nick.json");
                               })

五. View Component

  • Partial View Why not? Because the business logic can not add
  • If the Controller written inside it? It is impossible to reuse everywhere
  • ChildAction it? Too costly, it needs to finish the entire life cycle of the Controller

1. View Component

  • Like Partial View, but also it comes with a mini Controller, where you can also write business logic
  • Razor syntax can be used to render a View Component

ViewComponent / CompanySummaryViewComponent.cs :

public class CompanySummaryViewComponent: ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        // ...
        return View();
    }
}

六. Razor Page

  • All pages are placed in the MVC Pages directory

Seven. SignalR

  • Real-time Web applications (Server sends to the Client)

1. SignalR "bottom" technique

  • SignalR used three "underlying" technology to achieve real-time Web, they are Long Polling,

    Server Sent Events 和 WebSocket

1.1 Polling
  • Polling is a stupid way to achieve real-time Web, and it is through periodic sending a request to the server, data server to see if there is a change
  • If the data server does not change, it returns 204 No Content; if there is a change put the latest data is sent to the client
  • This is Polling, very simple, but more a waste of resources
  • This technology does not use Polling SignalR
1.2 Long Polling
  • Long Polling Polling and have a similar place, clients are sending requests to the server. But the difference is: If the server does not have new data to be sent to the client, then the server will remain connected until the new data are generated, the server only then the new data back to the client
  • If no request is made in response to a period of time, then the request will timeout. In this case, the client makes a request again
1.3 Server Sent Event(SSE)
  • Use SSE words, Web server can send data at any time to the browser, you can call it a push, and the browser will monitor incoming information, such as information flow, like data, this connection will remain open until the server closes it
  • The browser will use the object called EventSource used to pass over information processing

  • Individual, there is limit the number of connections, and only supports text type

1.4 Web Socket
  • Web Socket another TCP protocol different from HTTP, which enables interactive communication between the browser and the server becomes possible. Using a WebSocket, messages can be sent to the client from the server, the client may be sent by the server, HTTP and the like without delay. Information flow is not completed when, TCP Socket usually remain open
  • When using the line-generation browser, in most cases SignalR will use Web Socket, which is the most effective means of transmission
  • Full-duplex communication: the client and the server can send information to each other
  • SSE and is not that a browser connection limit (6), most browsers limit the number of connections on the Web Socket is 50
  • Message Type: You can be both text and binary, Web Socket also supports streaming media (audio and video)
  • In fact, a normal HTTP request also uses the TCP Socket. Web Socket Standard Socket uses a handshake mechanism to upgrade for the HTTP protocol using WS Web Socket socket
1.5 Web Socket Life Cycle
  • Everything happened inside the TCP Soket

​ TCP Socket

|__________________________________|

| HTTP handshake communication / data exchange closed |

|__________________________________|

1.6 HTTP handshake
  • Each Web Socket beginning is a simple HTTP Socket
  • The client first sends a GET request to the server to request an upgrade Socket
  • If the server agree, the Socket From this point on it becomes a Web Socket
GET/chat  HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw--
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
HTTP/1.1  101  Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmmSOPpG2HaGwk-
Sec-WebSocket-Protocol: chat
1.7 Message Type
  • Web Socket message types can be text, binary. Also includes a control message class: Ping / Pong, and closed
  • Each message consists of a Frame or more, each with a Frame (Frame information of this is shown) a head bytes

2. SignalR

  • SignalR is a .NET Core / open source real-time framework for the .NET Framework. SignalR may use Web Socket, Server Sent Event and Long Polling manner as the underlying transport
  • SignalR based on three technologies to build abstract on top of them, it makes you a better focus on the business problem rather than the underlying transmission technology issues
  • SignalRR This framework divides the server and the client, server-side support for ASP.NET Core and ASP.NET; and the client browser in addition to supporting the javascript outside, also supports other similar clients, such as desktop applications

3. SignalR down mechanism

  • Three kinds of underlying transport technologies are used SignalR Web Socket, Server Sent Event and Long Polling
  • Web Socket which supports only the more modern browsers, Web servers can not be too old
  • The Server Sent Event situation may be better, but there are the same problems
  • So SignalR using the drop mechanism, SignalR have the ability to negotiate the transfer type of support

4. RPC

  • RPC (Remote Procedure Call), it's a bit like that can invoke remote service calls as local method
  • SignalR RPC paradigm employed to communicate between the client and the server
  • SignalR to make use of the underlying transport server can call the method of the client, and vice versa, these methods can take parameters, parameters can also be complex objects, SignalR responsible for serialization and de-serialization

5. Hub

  • Hub is a component SignalR, which runs in ASP.NET Core applications where it is a server-side class
  • Hub using RPC to receive information sent from the client, a message can be sent to the client. So it is a communication of the Hub
  • In ASP.NET Core Lane, Hub class created their own need to inherit from a base class Hub
  • In the Hub inside the class, we can call methods on all clients, and clients can also call the same class inside the method Hub

  • Said before the method call when you can pass complex parameters, SignalR parameters can serialization and de-serialization, these parameters are serialized format called the Hub protocol, it is a kind of agreement Hub for serialization and de-serialization format
  • Hub protocol default protocol is JSON, yet another protocol support is MessagePack. MessagePack is a binary format, which is more compact than JSON, and dealing with them easier and faster, because it is binary
  • In addition, SignalR can also be used to expand other agreements

6. Scale (the application running on multiple servers: load balancing)

  • At this load balancer will ensure that for each request according to a certain logic may be assigned to a different server
  • Use the Web Socket is using, no problem, because once the Web Socket connection is established, as between the browser and the server to open the tunnel, the server will not switch
  • But if you use Long Polling, it may be a problem, because in the case of using the Long Polling, each time you send a request message is different, and each request could go to a different server. Different server may not know the contents of the previous server, which will cause problems
  • To address this issue, we need to use Sticky Sessions (sticky session)
  • Sticky Sessions looks like there are many ways to achieve, but this is the main way to introduce the following
  • As part of the response to the first request, a load balancer sets Cookie in the browser, used to indicate this server. In subsequent requests, the read load balancing cookies, and then requests to the same server

Guess you like

Origin www.cnblogs.com/dylan1iu/p/11881560.html