Program.cs
1    using AGSS.Models;
2    using AGSS.Models.Template;
3    using Microsoft.AspNetCore.Authentication.JwtBearer;
4    using Microsoft.EntityFrameworkCore;
5    using Microsoft.IdentityModel.Tokens;
6    
7    
8    
9    
10   
11   
12   
13   
14   
15   
16   
17   var builder = WebApplication.CreateBuilder(args);
18   
19   
20   
21   
22   var domain = builder.Configuration["Auth0:Domain"];
23   var audience =builder.Configuration["Auth0:Audience"];
24   
25   //数据库配置(PGSQL)
26   builder.Services.AddDbContext<DBContext>(opt =>
27       opt.UseNpgsql(builder.Configuration.GetConnectionString("DBContext")));
28   
29   //鉴权配置
30   builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
31           .AddJwtBearer(options =>
32           {
33               options.Authority = domain;
34               options.Audience = audience;
35               options.TokenValidationParameters = new TokenValidationParameters
36               {
37                   ValidateIssuer = true,
38                   ValidateAudience = true,
39                   ValidateLifetime = true,
40                   ValidIssuer = domain,
41                   ValidAudience = audience
42               };
43               options.Events = new JwtBearerEvents
44               {
45                   OnChallenge = context =>
46                   {
47                       context.HandleResponse();
48                       context.Response.StatusCode = 200;
49                       context.Response.ContentType = "application/json";
50                       return context.Response.WriteAsJsonAsync(new ReturnTemplate(401,"你提供了一个错误的Token,所以我们无法验证你的身份,唔......",null));
51                   }
52   
53               };
54           });
55   builder.Services.AddAuthorization();
56   
57   
58   
59   builder.Services.AddControllers();
60   // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
61   builder.Services.AddEndpointsApiExplorer();
62   builder.Services.AddSwaggerGen();
63   
64   var app = builder.Build();
65   
66   // 配置Swagger
67   if (app.Environment.IsDevelopment())
68   {
69       app.UseSwagger();
70       app.UseSwaggerUI();
71   }
72   
73   app.UseHttpsRedirection();
74   
75   app.UseAuthentication();
76   
77   app.UseAuthorization();
78   
79   //自定义中间件 把404变成200
80   app.Use(async (context, next) =>
81   {
82       await next(); // 先执行后续中间件
83       
84       // 如果响应是 404 且未修改过
85       if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
86       {
87           context.Response.StatusCode = 200; // 改为 200
88           context.Response.ContentType = "application/json";
89           
90           // 自定义响应内容
91           await context.Response.WriteAsJsonAsync(new ReturnTemplate(404,"未能找到资源吖!",null));
92       }
93   });
94   
95   //控制器路由
96   app.MapControllers();
97   
98   app.Run();
99