我開始學習 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());
uj5u.com熱心網友回復:
services.Add 是注冊服務,app.Use 是使用中間件的方式
Configure Service():用于向容器添加服務并配置這些服務。基本上,服務是一個用于應用程式中常見消費的組件。有MVC、EF核心、身份等框架服務。但也有特定于應用程式的應用程式服務,例如發送郵件服務。
Configure():它用于指定 asp.net 核心應用程式將如何回應單個請求。通過這個,我們實際上構建了 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!");
});
});
}
}
閱讀此示例以了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486765.html
