整合 Entity Framework 和 Swagger 配置

此次更改將 Entity Framework 和 Swagger 的配置整合進入 ASP.NET Core 應用程式中。新增了對 `Microsoft.EntityFrameworkCore` 和 `Microsoft.OpenApi.Models` 的引用,移除了原本的 `AddControllers` 和 `AddSwaggerGen` 方法。新增 `AddDbContext` 方法以配置 MySQL 資料庫的連接字串並設置重試機制。更新了 Swagger 的配置,並啟用了 CORS 和 HTTPS 重定向。
This commit is contained in:
Chen, Chun-Yi 2025-09-30 11:03:49 +08:00
parent 3af7cdcaa4
commit 9027f7d93d

View File

@ -1,12 +1,32 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using XisongSpaceBooking_BackEnd.Configurations;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllers(); builder.Services.AddControllers();
// °t¸m Entity Framework
builder.Services.AddDbContext<SpaceBookingDbContext>(options =>
{
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString),
mySqlOptions =>
{
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
});
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "¦èªQ°ª¤¤³õ¦a¹w¬ù/Xisong Space Booking API", Version = "v1" });
});
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
@ -16,6 +36,8 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI(); app.UseSwaggerUI();
} }
app.UseCors("AllowAll");
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthorization(); app.UseAuthorization();