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

If you for sure use a Web API project, you can:

  • enable Http Attribute Routing,
  • create the following method within an existing or new controller:
[Route(""), HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public HttpResponseMessage RedirectToSwaggerUi()
{
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found);
    httpResponseMessage.Headers.Location = new Uri("/swagger/ui/index", UriKind.Relative);
    return httpResponseMessage;
}

Note the use of ApiExplorerSettings attribute, so that it doesn't show up in the Swagger definition.


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.