Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing the error that swagger is already in the route collection for Web API 2?

I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.

My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.

In Package Console Manager run:

Install-Package Swashbuckle

To get your Test Web API controller working: 1) Comment this out in the WebApi.config:

// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

Now this URL: http://localhost:33515/api/Test brings back XML:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"     xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>

In Global.asax Register() I call:

 SwaggerConfig.Register();

In AppStart.Swagger.Config Register() I put:

public class SwaggerConfig
{
    public static void Register()
    {     
       var thisAssembly = typeof(SwaggerConfig).Assembly;
       GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1.0", "HRSA CHAFS");
                    c.IncludeXmlComments(GetXmlCommentsPath());
                })
              .EnableSwaggerUi(c =>
                {});
    }

    private static string GetXmlCommentsPath()
    {
        var path = String.Format(@"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
        return path;

    }
}

Now I get this error: "A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."

I've been stuck on this for hours. How do you get rid of this?

like image 651
Sam Avatar asked Feb 14 '17 21:02

Sam


2 Answers

This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.

Delete your bin folder and re-build your solution. This resolves the swagger error.

like image 196
MichaelD Avatar answered Oct 12 '22 23:10

MichaelD


Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
like image 43
opewix Avatar answered Oct 13 '22 01:10

opewix