1
votes

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?

1
Have you tried using the specific HTTP method attribute instead of the generic Route ? If your controller action should be mapped to accept GET method requests, use the [HttpGet("Error/Error/{statusCode}")] attribute. - jdewerth
Can you provide a minimum, reproducible example - Helder Sepulveda
@jandrew if i make it HttpGet the error in the swagger goes away. But the Error Action appears in the Swagger API - sm101
@sm101 Can clarify what you mean by "Error Action appears in the Swagger API" ? Are you getting another exception ? - jdewerth
@jandrew No What i meant was that if I make the method "HttpStatusCodeHandler()" actions, method attribute as HttpGet instead of Route, then in the Swagger API documentation which swagger generates, the Method gets exposed as an GET Endpoint. - sm101

1 Answers

0
votes

I removed the [Route("Error/Error/{statusCode}")] from the method and included the middleware app.UseStatusCodePagesWithRedirects() in the configure method.

I am not sure on the exact reason for the swagger API error.