32

I try to use Swagger with Microsoft WebAPI 2.

For the moment, I've the following call in a method.

appBuilder
   .ConfigureOAuth()
   .UseWebApi(configuration)
   .UseWelcomePage();

If I want to use Swagger, I must use this url "https://localhost:44300/swagger" which one works very well.

I want my home page redirects to the url of my swagger, perhaps as follows but this sample doesn't works.

    appBuilder
       ...
       .UseWelcomePage("/swagger");

Any idea ?

Ian Kemp
  • 24,155
  • 16
  • 97
  • 121
Philippe Matray
  • 1,471
  • 1
  • 13
  • 22
  • i want similar thing, did you get this finally working, I am using it exactuly the way you use it but doesn't work ... – user1829319 Jul 11 '15 at 03:02
  • Change launchSettings file instead of trying to hack around with routes and default locations. https://stackoverflow.com/a/30002051/706363 – Piotr Kula Nov 28 '18 at 10:39

12 Answers12

58

I got this working how I wanted by adding a route in RouteConfig.cs like so:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "swagger_root", 
            routeTemplate: "", 
            defaults: null, 
            constraints: null,
            handler: new RedirectHandler((message => message.RequestUri.ToString()), "swagger"));

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

See this code from swashbuckle to see what's going on: https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Application/RedirectHandler.cs

patrickbadley
  • 2,167
  • 1
  • 24
  • 24
18

In the Startup.cs file in the Configuration(IAppBuilder app) method I used this line of code to cause it to redirect on load to the swagger welcome page.

app.Run(async context => { 
    context.Response.Redirect("swagger/ui/index"); 
}); 

So the full method I am using is as follows

[assembly: OwinStartup(typeof(AtlasAuthorizationServer.Startup))]
namespace AtlasAuthorizationServer
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);

            app.Run(async context => {
                context.Response.Redirect("swagger/ui/index");
            });
        }
    }
}

Note that this is going to cause a green warning in visual studio. I am sure there is some way to mimic this as asynchronous with an await call in the function.

Brad LaPratt
  • 181
  • 1
  • 3
13

For Asp.Net core use this:

app.Run(context => {
            context.Response.Redirect("swagger/ui");
            return Task.CompletedTask;
        });
Rui Eusebio
  • 131
  • 1
  • 2
  • 2
    with the latest version, I just redirect to "swagger" and not "swagger/ui" - works a treat though. – Ross Vernal Oct 26 '17 at 09:51
  • While the redirect works, the service is not working. I get error 'TypeError: Failed to fetch' with this. Removing this, return my apps to working state. Please test your answer properly. – Syaiful Nizam Yahya Mar 14 '18 at 02:55
6

Ok, here is one way of doing it. Add a new MVC controller (Not Web API) e.g HomeController and in the Index action add the following code:

using System.Web.Mvc;

namespace Kids.Math.Api.Controllers
{
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new RedirectResult("~/swagger/ui/index");
    }


}

}

Also, make sure your route config has the follow (Note, by default it already does)

        public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
user1829319
  • 541
  • 7
  • 21
6

If you've come here looking for the asp.net core 2 answer you can acheive the same by setting the RoutePrefix of swagger to the apps root

app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My service");
                c.RoutePrefix = string.Empty;  // Set Swagger UI at apps root
            });

How to redirect root to swagger in Asp.Net Core 2.x?

Calvin V
  • 101
  • 2
  • 4
5

In ASP.NET Core, you can simply just change the RoutePrefix when registering SwaggerUI to empty string.

app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "";
    ...
};

No redirect configuration required, unless you still want /swagger or something similar in the path.

Adrian Sanguineti
  • 2,252
  • 1
  • 23
  • 27
  • This doesn't work w/`c.SwaggerEndpoint("/swagger/v1/swagger.json")` or with `c.SwaggerEndpoint("../swagger/v1/swagger.json")` once deployed ... It can't find the `.json` file. Need to add base path to the endpoint string: https://stackoverflow.com/a/44937002/3216970 – mc01 Jul 13 '18 at 19:28
  • 3
    To clear up what @mc01 is saying, this answer will not work if you're hosting the Web API in a virtual directory. If that's not your usecase (i.e. you're deploying to its own website in IIS, or to its own App Service in Azure), then this answer works perfectly fine. – Adrian Sanguineti Dec 05 '18 at 23:27
2

I had similar problem and I solved it by customizing SwaggerUI url. This is my Configuration method:

public void Configuration(IAppBuilder app)
{
    var thisAssembly = typeof (Startup).Assembly;

    HttpConfiguration httpConfig = new HttpConfiguration();

    app.MapHttpAttributeRoutes();
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(httpConfig);

    httpConfig
        .EnableSwagger("api/{apiVersion}",c =>
        {
            c.IncludeXmlComments(string.Format(@"{0}\bin\Docs.xml", AppDomain.CurrentDomain.BaseDirectory));
            c.SingleApiVersion("v1", "My API");
        })
        .EnableSwaggerUi("{*assetPath}",c =>
        {
            c.CustomAsset("index", thisAssembly, "AspNetIdentity.WebApi.DocsAssets.index.html");
        });

    httpConfig.Routes.First(x => x.RouteTemplate == "{*assetPath}").Defaults["assetPath"] = "index";
}

This way when You go to localhost:44300 You'll get Swagger UI as startup page.

Misiu
  • 4,406
  • 13
  • 82
  • 174
2

What you can do, just set Home Controller & Index Action as your Default, and modify your controller action as below:

public class HomeController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return new RedirectResult("~/swagger");
    }
}

Short and quick solution to this problem.

1

In .Net Core, just open Properties of the application, go to Debug tab, and write Swagger in the "Launch browser" text box,

launch browser

  • 3
    This only works when debugging locally. The goal is to use Swagger UI as home page when deployed. – mc01 Jul 12 '18 at 21:29
0

For ASP.NET Core the following pull request was created: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/486

In the meantime the following workaround can be used:

public static IApplicationBuilder UseSwaggerUI(
        this IApplicationBuilder app,
        Action<SwaggerUIOptions> setupAction)
    {
        var options = new SwaggerUIOptions();
        setupAction?.Invoke(options);

        // This method reads an internal property value 
        // http://dotnetfollower.com/wordpress/2012/12/c-how-to-set-or-get-value-of-a-private-or-internal-property-through-the-reflection/
        var indexSettings = options.GetPropertyValue<IndexSettings>("IndexSettings");
        // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider
        // to inject parameters into "index.html"
        var fileServerOptions = new FileServerOptions
        {
            RequestPath = string.IsNullOrWhiteSpace(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}",
            FileProvider = new SwaggerUIFileProvider(indexSettings.ToTemplateParameters()),
            EnableDefaultFiles = true,
            StaticFileOptions =
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider()
            }
        };
        app.UseFileServer(fileServerOptions);

        return app;
    }

Cheers

Guilherme Duarte
  • 3,156
  • 1
  • 26
  • 34
0

Following the example from here:

https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=visual-studio

public class Startup {
   public void Configure(IApplicationBuilder app) {
      ...
      app.UseSwaggerUI( c => {
         c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
         c.RoutePrefix = string.Empty;
      });
      app.UseMvc(); // <-- must be after 
   }
}

I couldn't get it to work until I placed the app.UseMvc() after the call to app.UseSwaggerUI().

Ian
  • 494
  • 4
  • 8
0

Asp Net Core > 2.2 in a RestFUL API, just set the default url in the Project/Properties/Debug settings

ASP Net Core >2.2 RestFUL API

JimbobTheSailor
  • 887
  • 7
  • 16