Parking_space_ASPNET/Parking_spaces/Program.cs
2024-02-01 11:37:15 +08:00

131 lines
2.9 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Parking_spaces.Authorization;
using Parking_spaces.Helpers;
using Parking_spaces.Services;
/*
var builder = WebApplication.CreateBuilder(args);
// 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"));
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IUserService, UserService>();
}
var app = builder.Build();
// configure HTTP request pipeline
{
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
}
app.Run();
*/
var builder = WebApplication.CreateBuilder(args);
//身分驗證
//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"));
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IUserService, UserService>();
// 注册 HttpClient 服务
services.AddHttpClient();
}
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
builder.Services.AddCors();
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
//身分驗證
// configure HTTP request pipeline
{
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
pattern: "{controller=Home}/{action=Login}/{id?}");
app.Run();