How to use Swagger as Welcome Page of IAppBuilder in WebAPI

允我心安 提交于 2019-11-29 23:59:40

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

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.

For Asp.Net core use this:

app.Run(context => {
            context.Response.Redirect("swagger/ui");
            return Task.CompletedTask;
        });

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 }
        );
    }

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.

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.

You could setup some routing in your configuration object. Hard to tell the full detail as your code snippet is limited. Hope this points you in the right direction.

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

launch browser

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?

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

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.

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!