如何在 ASP.NET Core 7 Web API 中为所有端点设置前缀?

问题描述 投票:0回答:1

我正在从我的

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();

但我还是得不到想要的结果。

我做错了什么?

asp.net-core-webapi .net-7.0 asp.net-web-api-routing
1个回答
0
投票

配置 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();
}

测试

© www.soinside.com 2019 - 2024. All rights reserved.