ASP.NET Core 启动类中的 services.Add 和 app.Use 有什么区别?

Moh*_*wad 3 c# asp.net-core

我开始学习 ASP.NET Core,在 Web API 模板的框架内,有一个带有和方法Startup的类。ConfigureServices()Configure()

谁能告诉我如何使用它们?我正在观看 Udemy 课程,但我不明白讲师为什么这样做

public class Startup
{
    private readonly IConfiguration config;

    public Startup(IConfiguration config)
    {
        this.config = config;
    }

    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.AddApplicationServices(this.config);
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPIv5", Version = "v1" });
        });
        services.AddCors();
        services.AddIdentityServices(this.config);

    }

    // 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();
        //    app.UseSwagger();
        //    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPIv5 v1"));
        //}
        app.UseMiddleware<ExceptionMiddleware>();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(x => x
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .SetIsOriginAllowed(origin => true) // allow any origin
                   .AllowCredentials());
Run Code Online (Sandbox Code Playgroud)

Qin*_*Guo 5

services.Add 是注册服务,是使用中间件的app.Use 方式

Configure Service():用于向容器添加服务并配置这些服务。基本上,服务是一个供应用程序中共同使用的组件。有MVC、EF core、identity等框架服务。但也有特定于应用程序的应用程序服务,例如发送邮件服务。

Configure():它用于指定 ASP.NET Core 应用程序如何响应各个请求。通过这个,我们实际上构建了HTTP请求管道

public class Startup {
        
        // This method gets called by the runtime. 
          // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Register services here through dependency injection
        }
  
        // This method gets called by the runtime. 
          // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, 
                              IWebHostEnvironment env) {
            
            // Add middlware components here
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                endpoints.MapGet("/",async Context => {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

阅读此示例以了解更多信息。