标准形式的启动

发布时间 2023-07-30 08:22:12作者: 张志恒的博客
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Hosting;
 6 using Microsoft.Extensions.Configuration;
 7 using Microsoft.Extensions.Hosting;
 8 using Microsoft.Extensions.Logging;
 9 
10 namespace WebApplication1
11 {
12     public class Program
13     {
14         public static void Main(string[] args)
15         {
16             CreateHostBuilder(args).Build().Run();    //通过环境参数,建立一个host
17         }
18 
19         public static IHostBuilder CreateHostBuilder(string[] args) =>
20             Host.CreateDefaultBuilder(args)
21                 .ConfigureWebHostDefaults(webBuilder =>
22                 {
23                     webBuilder.UseStartup<Startup>();            //WebHostBuilder
24                 });
25     }
26 }
入口
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.Http;
 8 using Microsoft.Extensions.DependencyInjection;
 9 using Microsoft.Extensions.Hosting;
10 
11 namespace WebApplication1
12 {
13     public class Startup
14     {
15         // This method gets called by the runtime. Use this method to add services to the container.
16         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
17         public void ConfigureServices(IServiceCollection services)          //将注册服务和使用服务分开
18         {
19         }
20 
21         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
22         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
23         {
24             if (env.IsDevelopment())                                //开发环境        
25             {
26                 app.UseDeveloperExceptionPage();
27             }
28 
29             app.UseRouting();                                                                     
30 
31             app.UseEndpoints(endpoints =>                          //给一个get请求的地址             
32             {
33                 endpoints.MapGet("/", async context =>
34                 {
35                     await context.Response.WriteAsync("Hello World!");
36                 });
37             });
38         }
39     }
40 }
配置和使用中间件