【发布时间】:2022-07-26 03:07:05
【问题描述】:
我开始学习 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());
【问题讨论】:
-
最短的答案是
app.Use向管道添加中间件,services.Add在 IoC(服务)容器中注册服务。但是,您可能需要一些背景知识才能了解这一点,而最短的解释可能还不够。然后建议学习如何构建自定义中间件以及如何注册自定义服务(以及用于什么目的)。那么区别应该更清楚了。 -
我会在课程中做到这一点,谢谢
标签: c# asp.net-core