我创建了一个 .NET Core 8.0 Web api 我添加了两个类,它们代表具有相同内部类的 api 响应。
public class House
{
public Dimensions dimensions { get; set; }=new Dimensions();
public class Dimensions
{
public int Height { get; set; }
public int Width{ get; set; }
}
}
public class Garage
{
public Dimensions dimensions { get; set; } = new Dimensions();
public class Dimensions
{
public int Height { get; set; }
public int Width{ get; set; }
}
}
我已向默认 WeatherForecast 控制器添加了方法,每个方法都返回以下响应类之一:
[HttpGet(Name = "GetHouse")]
public House GetHouse()
{
return new House();
}
[HttpGet(Name = "GetGarage")]
public Garage GetGarage()
{
return new Garage();
}
当我运行应用程序时,我收到了 swagger 页面,上面写着
无法加载API定义
获取错误 内部服务器错误http://localhost:2965/swagger/v1/swagger.json
我打开http://localhost:2965/swagger/v1/swagger.json,我看到以下内容:
处理请求时发生未处理的异常。 SwaggerGeneratorException:操作的冲突方法/路径组合“GET WeatherForecast” - Net8WebApi.Controllers.WeatherForecastController.Get (Net8WebApi)、Net8WebApi.Controllers.WeatherForecastController.GetHouse (Net8WebApi)、Net8WebApi.Controllers.WeatherForecastController.GetGarage (Net8WebApi)。对于 Swagger/OpenAPI 3.0,操作需要独特的方法/路径组合。使用 ConflictingActionsResolver 作为解决方法 Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable apiDescriptions,SchemaRepository schemaRepository)
问题是否出在相同的班级上?
有办法解决这个问题吗?招摇配置?
[HttpGet(Name = "GetGarage")]
-> 并不意味着将路线设置为Get: /WeatherForecast/GetGarage
,它只是意味着为路线命名。
对路由的URL匹配行为没有影响。仅使用 用于生成 URL。
因此,为了解决您的问题,我们可以将属性更改为
[HttpGet("GetHouse")]
和[HttpGet("GetGarage")]
。
但是我们将面临另一个例外
无法生成类型的架构 - WebApiNet8.Controllers.Garage。 查看内部异常 ---> System.InvalidOperationException: 无法使用 类型“$WebApiNet8.Controllers.Dimensions”的 schemaId“$Dimensions”。 相同的 schemaId 已用于类型 “$WebApiNet8.Controllers.House+Dimensions”
这是因为
Dimensions
和 class House
具有相同的类 class Garage
。我不确定你为什么这样定义类。如果没有具体原因,我们可以将 public class Dimensions
移出 House
和 Garage
类来解决这个异常。