Swagger 没有为第二种方法生成 json 文件

Swagger not producing json file for the second method

好的,我有一个控制器和两个功能,但是当我试图在 url 中大摇大摆时,我无法加载 json 文件,但我认为它与多个操作有关一样

产生错误

Fetch errorInternal Server Error /swagger/v1/swagger.json

我尝试了另一个问题建议的这条线

c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

但是这从 swagger 文档视图中隐藏了该方法,因此人们如何能够测试它们。我的控制器有什么问题吗?

public class BmiInformationsController : ControllerBase
{
    private readonly AppManagerDBContext _context;

    public BmiInformationsController(AppManagerDBContext context)
    {
        _context = context;
    }
    [HttpGet]
    public async Task<ActionResult<IEnumerable<BmiInformation>>> GetBmiInformation() {
        return await _context.BmiInformation.ToListAsync();
    }

    // GET: api/BmiInformations
    [HttpGet]
    public async Task<ActionResult<IEnumerable<BmiInformation>>> GetBmiInformationByUserId(string id)
    {
        return await _context.BmiInformation.Where(w => w.TennentId == new Guid(id)).ToListAsync();
    }        
}

这就是我配置 swagger 的方式

 services.AddSwaggerGen(c => {
   c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });
   c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

   c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
   Description = "JWT Authorization header using the Bearer scheme.",
   Name = "Authorization",
   In = ParameterLocation.Header,
   Type = SecuritySchemeType.Http,
   Scheme = "bearer",
   BearerFormat = "JWT"

 });

我的启动文件中的路线。

app.UseEndpoints(endpoints => {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
});

在控制器和操作方法上方添加具有 [Route] 属性的显式路由,如下所示:

[ApiController]
[Route("api")]
public class BmiInformationsController : ControllerBase
{
    private readonly AppManagerDBContext _context;

    public BmiInformationsController(AppManagerDBContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("bmi/all")]
    public async Task<ActionResult<IEnumerable<BmiInformation>>> GetBmiInformation() {
        return await _context.BmiInformation.ToListAsync();
    }

    // GET: api/BmiInformations
    [HttpGet]
    [Route("bmi/{id}")]
    public async Task<ActionResult<IEnumerable<BmiInformation>>> GetBmiInformationByUserId(string id)
    {
        return await _context.BmiInformation.Where(w => w.TennentId == new Guid(id)).ToListAsync();
    }        
}

设置显式路由时,不再有冲突的动作,swagger 可以同时显示这两个动作。

您也可以删除 c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());(这就是为什么 swagger.json 中没有包含第二种方法的原因,您只采用第一种方法以防路由冲突)。