在控制器中添加新的方法会导致Swagger出现500错误。

3
好久没写API了。现在我再次看了一下,并尝试简单地给WeatherForecastController添加一个get方法。但是在添加后,我一直收到一个swagger错误。这个方法看起来和现有的方法非常相似,只是多了一个参数。但是在添加后,我在浏览器中一直收到一个错误,我不确定为什么。我已经很久没有做这个了,而且以前从未使用过swagger。

Screenshot

请注意,我只是创建了这个项目并添加了方法,这就是我所做的一切。这是浏览器错误。

Screenshot


1
也许,正如这个答案中详细说明的那样,这里缺少的信息是:你不应该使用占位符Name。移除占位符并只使用字符串构造函数,或者使用Template占位符。但要注意参数amount。如果你不将其插入模板中,你只能通过查询字符串传递它。 - Alielson Piffer
4个回答

6
[Route("[controller]")] 改为 [Route("[controller]/[action]")]

3

试一下这个;

[HttpGet("GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

[HttpGet("GetNumberOfForecasts/{amount}")]
public IEnumerable<WeatherForecast> GetAmount(int amount)
{
    return Enumerable.Range(1, amount).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

1

仅供将来参考。

步骤1:-> 打开您的开发工具,或者只需按F12键。

      Then open the network tab, and refresh your page.

enter image description here

步骤 2:> 点击 swagger 调用并点击响应选项卡。

您将看到以下错误:

Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException:WebApplication1.Controllers.WeatherForecastController.Get (WebApplication1),WebApplication1.Controllers.WeatherForecastController.GetAmount (WebApplication1) 的方法/路径组合冲突 "GET WeatherForecast"。 Swagger/OpenAPI 3.0 需要一个唯一的方法/路径组合。使用 ConflictingActionsResolver 作为解决方法。

enter image description here

尝试像这样进行路由

enter image description here

结果

enter image description here


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接