Technology Sharing

There is no Startup class and ConfigureServices method in the ASP.NET Core webapi project created by .NET6

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

The role of Startup.cs is to register static files, pipelines, services, logs, routes, database connections, filters, etc. used in the project.

If there is no startup.cs, you can manually create a new Startup.cs class (The specific code can be modified according to your own situation

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration)
  4. {
  5. Configuration = configuration;
  6. }
  7. public IConfiguration Configuration { get; }
  8. //在依赖注入容器中注册服务
  9. public void ConfigureServices(IServiceCollection services)
  10. {
  11. services.AddSingleton<IDbConfig.IDbConfig, DbConfig.DbConfig>();
  12. services.AddTransient<IBaseService, BaseService>();
  13. services.AddControllers();
  14. services.AddSwaggerGen(c =>
  15. {
  16. c.SwaggerDoc("v1", new OpenApiInfo { Title = "这里填写项目的名称", Version = "v1" });
  17. });
  18. }
  19. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  20. {
  21. if(env.IsDevelopment())
  22. {
  23. app.UseDeveloperExceptionPage();
  24. app.UseSwagger();
  25. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "这里填写项目的名称 v1"));
  26. }
  27. app.UseRouting();
  28. app.UseAuthorization();
  29. app.UseEndpoints(endpoints =>
  30. {
  31. endpoints.MapControllers();
  32. });
  33. }
  34. }

After writing the above, you can go to the second step

Program.cs internal update logic

All the objects required by the Startup.cs class are present in the builder object, so we can pass the required objects to the and methods.

  1. var builder = WebApplication.CreateBuilder(args);
  2. var startup = new Startup(builder.Configuration);
  3. startup.ConfigureServices(builder.Services);
  4. var app = builder.Build();
  5. startup.Configure(app, builder.Environment);