From 9027f7d93da29b4beec1fbca689740f3b6ca68a1 Mon Sep 17 00:00:00 2001 From: Chunyi Date: Tue, 30 Sep 2025 11:03:49 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B4=E5=90=88=20Entity=20Framework=20?= =?UTF-8?q?=E5=92=8C=20Swagger=20=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此次更改將 Entity Framework 和 Swagger 的配置整合進入 ASP.NET Core 應用程式中。新增了對 `Microsoft.EntityFrameworkCore` 和 `Microsoft.OpenApi.Models` 的引用,移除了原本的 `AddControllers` 和 `AddSwaggerGen` 方法。新增 `AddDbContext` 方法以配置 MySQL 資料庫的連接字串並設置重試機制。更新了 Swagger 的配置,並啟用了 CORS 和 HTTPS 重定向。 --- XisongSpaceBooking_BackEnd/Program.cs | 28 ++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/XisongSpaceBooking_BackEnd/Program.cs b/XisongSpaceBooking_BackEnd/Program.cs index 48863a6..1830afa 100644 --- a/XisongSpaceBooking_BackEnd/Program.cs +++ b/XisongSpaceBooking_BackEnd/Program.cs @@ -1,12 +1,32 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; +using XisongSpaceBooking_BackEnd.Configurations; + var builder = WebApplication.CreateBuilder(args); // Add services to the container. - builder.Services.AddControllers(); + +// tm Entity Framework +builder.Services.AddDbContext(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 builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - +builder.Services.AddSwaggerGen(c => +{ + c.SwaggerDoc("v1", new OpenApiInfo { Title = "Qaw/Xisong Space Booking API", Version = "v1" }); +}); var app = builder.Build(); // Configure the HTTP request pipeline. @@ -16,6 +36,8 @@ if (app.Environment.IsDevelopment()) app.UseSwaggerUI(); } +app.UseCors("AllowAll"); + app.UseHttpsRedirection(); app.UseAuthorization();