How to redirect from root url to /swagger/ui/index?

v.karbovnichy picture v.karbovnichy · Jun 9, 2016 · Viewed 20.3k times · Source

I have a WebApi project with Swashbuckle installed onto it.

In default setup, I must open in browser http://localhost:56131/swagger/ui/index to view my operations description and test page. I want it to be accessible from root of the site: http://localhost:56131/. How can I achieve this?

Answer

v.karbovnichy picture v.karbovnichy · Dec 22, 2016

Influenced by this answer to similar question, slightly modified code:

public class WebApiConfig
{
    public static void Configure(IAppBuilder app)
    {
        var httpConfig = new HttpConfiguration();

        // Attribute routing
        config.MapHttpAttributeRoutes();

        // Redirect root to Swagger UI
        config.Routes.MapHttpRoute(
            name: "Swagger UI",
            routeTemplate: "",
            defaults: null,
            constraints: null,
            handler: new RedirectHandler(SwaggerDocsConfig.DefaultRootUrlResolver, "swagger/ui/index"));

        // Configure OWIN with this WebApi HttpConfiguration
        app.UseWebApi(httpConfig);
    }
}

This way it is not necessary to create new WebAPI controller as so did @bsoulier in his answer.

This solution is based on already existing class RedirectHandler in Swashbuckle.Core assembly.