我正在从我的
appsettings.json
中检索字符串:
{
"ConnectionStrings": {
//several strings
},
"BaseRoute": {
"Base": "/myapi/"
}
}
我有课:
public class BaseRoute
{
public string Base { get; set; }
}
在我的
Program.cs
中我已配置:
var builder = WebApplication.CreateBuilder(args);
// ...
builder.Services.Configure<BaseRoute>(builder.Configuration.GetSection("BaseRoute"));
var baseroute = builder.Configuration.GetSection("BaseRoute").Get<BaseRoute>();
builder.Services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<BaseRoute>>().Value);
// ...
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<JwtRefresher>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UsePathBase(new PathString(baseroute.Base));
app.UseRouting();
app.Run();
但是当我运行 api 时,我的 Swagger 端点中没有设置前缀。 我该如何解决这个问题?
我什至尝试将
app.UsePathBase(new PathString("/api"));
放在更高的位置:
var app = builder.Build();
app.UsePathBase(new PathString(baseroute.Base));
app.UseRouting();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<JwtRefresher>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
或者将 PathString 参数中的变量替换为固定字符串:
var app = builder.Build();
app.UsePathBase(new PathString("/api"));
app.UseRouting();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<JwtRefresher>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
但我还是得不到想要的结果。
我做错了什么?
配置 swagger 如下:
app.UsePathBase(new PathString("/api"));
app.UseRouting();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
var basePath = "/api";
app.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/swagger.json";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
});
});
app.UseSwaggerUI();
}