Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger API breaks when Route attribute is set to Controller Action - ASP.NET Core

I am using ASP.NET Core 3.1. In My Web Application I have integrated swagger. Which works fine, shows the endpoints properly in the swagger API documentation. The code in startup is as below:

public void ConfigureServices(IServiceCollection services)
{
            services.AddSwaggerGen( c => {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });
}

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Clients}/{action=Index}/{id?}");
            });

            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Push Notification API V1");
            });

         }

To my Error Controller I just added a HttpStatusCodeHandler method and gave a route as below. Then the swagger gives a error as:

"Failed to load API definition." Fetch error undefined /swagger/v1/swagger.json

The method code is as follows.

[Route("Error/Error/{statusCode}")]
public IActionResult HttpStatusCodeHandler(int statusCode)
{
    switch (statusCode)
    {
        case 404:
            ViewBag.ErrorMessage = "Sorry, the resource you requested could not be found.";
            break;
    }
    return View("Error");
}

Every time I comment out the Route attribute [Route("Error/Error/{statusCode}")] the swagger API works fine. What could be the error in this?

like image 754
sm101 Avatar asked Nov 01 '25 14:11

sm101


1 Answers

The root cause is your controller is recognized as ApiController if you add Route attribute, and swagger will be broken if you do not add HttpMethod attribute in your controller.

Add [ApiExplorerSettings(IgnoreApi = true)] attribute to your controller, and the swagger broken problem should be fixed.

like image 73
frank_lee Avatar answered Nov 04 '25 08:11

frank_lee