parking-webapi/WebApi_data_value/Program.cs

180 lines
5.4 KiB
C#
Raw Normal View History

2024-09-28 01:25:42 +08:00

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Configuration;
using System.Reflection;
using System.Text;
using Parking_space_WebAPI.Authorization;
using Parking_space_WebAPI.Helpers;
using Parking_space_WebAPI.Services;
2024-10-01 02:30:08 +08:00
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using Parking_space_WebAPI.BackgroundServices;
2024-09-28 01:25:42 +08:00
var builder = WebApplication.CreateBuilder(args);
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
builder.Services.AddCors();
// Add services to the container.
builder.Services.AddControllers();
2024-10-01 02:30:08 +08:00
//執行每日存取剩餘車位
builder.Services.AddScoped<ExcelGenerationService>(); // ExcelGenerationService 註冊為 Scoped
builder.Services.AddHostedService<DailyExcelGenerationService>(); // DailyExcelGenerationService 註冊為 HostedService
2024-09-28 01:25:42 +08:00
// 註冊 BackgroundService
builder.Services.AddHostedService<ParkingUpdateService>(); //執行每一分鐘更新剩餘車位
// 連線PostgreSQL資料庫
var connectionString = "Server=140.125.20.183;UserID=postgres;password=EL404el404;Database=postgres;port=5432;Search Path=public;CommandTimeout=1800";
//var connectionString = "Server=127.0.0.1;UserID=postgres;password=EL404el404;Database=postgres;port=5432;Search Path=public;CommandTimeout=1800";
builder.Services.AddDbContext<SqlContext>(opt => opt.UseNpgsql(connectionString));
//連線MySQL資料庫
/*
builder.Services.AddDbContext<SqlContext>(opt =>
{
string connectionString = builder.Configuration.GetConnectionString("tarefasConnection");
var serverVersion = ServerVersion.AutoDetect(connectionString);
opt.UseMySql(connectionString, serverVersion);
});
*/
//身分驗證
//add services to DI container
{
var services = builder.Services;
services.AddCors();
services.AddControllers();
// configure strongly typed settings object
services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// 配置JWT身份验证
var jwtSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
//ValidIssuer = "your_issuer",
// ValidAudience = "your_audience",
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Parking_space_WebAPI", Version = "v1" });
// Configure Swagger to use JWT authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
// 将JWT令牌作为所有端点的要求添加到Swagger文档
//ˇc.OperationFilter<SecurityRequirementsOperationFilter>();
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IUserService, UserService>();
// 注册 HttpClient 服务
services.AddHttpClient();
}
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("校園外網", new OpenApiInfo
{
Version = "校園外網",
Title = "校園外網",
});
c.SwaggerDoc("校園大內網", new OpenApiInfo
{
Version = "校園大內網",
Title = "校園大內網",
});
});
//註解
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
// app.UseSwagger();
// app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI(c=>
{
c.SwaggerEndpoint("/swagger/校園外網/swagger.json", "校園外網");
c.SwaggerEndpoint("/swagger/校園大內網/swagger.json", "校園大內網");
});
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();