Search code examples
c#asp.net-coreswagger

Receiving Swagger error in .Net Core 8.0 Web Api


I created a .NET Core 8.0 web api I have added two classes that represent api responses that have an identical inner class.

 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; }
     }
 }

I have added to methods to the default WeatherForecast controller, that each return one of these response classes:

 [HttpGet(Name = "GetHouse")]
 public House GetHouse()
 {
     return new House();
 }

 [HttpGet(Name = "GetGarage")]
 public Garage GetGarage()
 {
     return new Garage();
 }

When I run the application, I am getting the swagger page, and it says

Failed to load API Definition

Fetch error Internal Server Error http://localhost:2965/swagger/v1/swagger.json

I open http://localhost:2965/swagger/v1/swagger.json and I see the following:

An unhandled exception occurred while processing the request. SwaggerGeneratorException: Conflicting method/path combination "GET WeatherForecast" for actions - Net8WebApi.Controllers.WeatherForecastController.Get (Net8WebApi),Net8WebApi.Controllers.WeatherForecastController.GetHouse (Net8WebApi),Net8WebApi.Controllers.WeatherForecastController.GetGarage (Net8WebApi). Actions require a unique method/path combination for Swagger/OpenAPI 3.0. Use ConflictingActionsResolver as a workaround Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable apiDescriptions, SchemaRepository schemaRepository)

Could the issue be the identical classes?

Is there a way around this? A swagger configuration?


Solution

  • [HttpGet(Name = "GetGarage")] -> doesn't mean to set the route to be Get: /WeatherForecast/GetGarage, it only means to give a name for the route.

    Have no impact on the URL matching behavior of routing. Are only used for URL generation.

    Therefore, to solve your issue, we can change the attribute to [HttpGet("GetHouse")] and [HttpGet("GetGarage")].

    But we will face another exception

    Failed to generate schema for type - WebApiNet8.Controllers.Garage. See inner exception ---> System.InvalidOperationException: Can't use schemaId "$Dimensions" for type "$WebApiNet8.Controllers.Dimensions". The same schemaId is already used for type "$WebApiNet8.Controllers.House+Dimensions"

    This is due to having the same class Dimensions both in class House and class Garage. I'm not sure why you define the classes like this. If there's no specific reason, we can move the public class Dimensions out of the House and Garage class to solve this exception.