介绍
Startup类是ASP.NET Core Web应用的启动类。在Program.cs中后面有一行 webBuilder.UseStartup
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using WebApplication3.Model;
namespace WebApplication3
{
public class Startup
{
public Startup(IConfiguration configuration) // 程序配置接口
{
Configuration = configuration;
}
// IConfiguration 程序配置接口,用来读取文件和内存中的配置
public IConfiguration Configuration { get; }
// 这个方法用于处理中间件/配置服务,在时候被执行
// IServiceCollection服务配置接口,用来配置常用服务及依赖注入
public void ConfigureServices(IServiceCollection services) // 注入
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "WebApplication3", Version = "v1"});
});
}
// IApplicationBuilder应用配置接口,用来配置中间件,所有的中间件都写在这个下面
// IWebHostEnvironment主机环境,用于不同环境不同处理
// 这个方法仅仅用来注册中间件,只会执行一次,主机run的时候执行,执行的目的是把以下中间件添加到管道里
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) // 判断是不是一个开发模式
{
app.UseDeveloperExceptionPage();//提供了一个开发人员异常页面(即捕捉异常的代码在最前面)
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication3 v1"));
} // 可以放在方法开头
app.UseHttpsRedirection(); //使用Https
app.UseRouting(); // 路由中间件
app.UseAuthorization(); // 启用身份验证
// 终端中间件
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}