简体   繁体   English

如何在 WebAPI 中使用 Swagger 作为 IAppBuilder 的欢迎页面

[英]How to use Swagger as Welcome Page of IAppBuilder in WebAPI

I try to use Swagger with Microsoft WebAPI 2.我尝试将Swagger与 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.如果我想使用 Swagger,我必须使用这个 url “ https://localhost:44300/swagger ”,它非常有效。

I want my home page redirects to the url of my swagger, perhaps as follows but this sample doesn't works.我希望我的主页重定向到我 swagger 的 url,可能如下所示,但此示例不起作用。

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

Any idea ?任何的想法 ?

I got this working how I wanted by adding a route in RouteConfig.cs like so:我通过在 RouteConfig.cs 中添加一个路由来按照我想要的方式工作,如下所示:

    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从 swashbuckle 查看此代码以了解发生了什么: 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.在 Configuration(IAppBuilder app) 方法的 Startup.cs 文件中,我使用这行代码使其在加载时重定向到 swagger 欢迎页面。

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.请注意,这将导致 Visual Studio 中出现绿色警告。 I am sure there is some way to mimic this as asynchronous with an await call in the function.我确信有一些方法可以通过函数中的 await 调用将其模拟为异步。

For Asp.Net core use this:对于 Asp.Net 核心使用这个:

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) eg HomeController and in the Index action add the following code:添加一个新的 MVC 控制器(不是 Web API),例如 HomeController 并在 Index 操作中添加以下代码:

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

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如果您来这里寻找 asp.net core 2 的答案,您可以通过将 RoutePrefix 的 swagger 设置为应用程序根目录来实现相同的效果

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? 如何在 Asp.Net Core 2.x 中将 root 重定向到 swagger?

In ASP.NET Core, you can simply just change the RoutePrefix when registering SwaggerUI to empty string.在 ASP.NET Core 中,您可以在将 SwaggerUI 注册为空字符串时简单地更改 RoutePrefix。

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

No redirect configuration required, unless you still want /swagger or something similar in the path.不需要重定向配置,除非您仍然需要/swagger或路径中的类似内容。

I had similar problem and I solved it by customizing SwaggerUI url.我有类似的问题,我通过自定义 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.这样,当您转到localhost:44300您将获得 Swagger UI 作为启动页面。

What you can do, just set Home Controller & Index Action as your Default, and modify your controller action as below:您可以做什么,只需将 Home Controller & Index Action 设置为您的默认值,然后修改您的控制器操作,如下所示:

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

Short and quick solution to this problem.这个问题的简短而快速的解决方案。

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,在 .Net Core 中,只需打开应用程序的 Properties,转到 Debug 选项卡,然后在“Launch browser”文本框中写入 Swagger,

launch browser启动浏览器

For ASP.NET Core the following pull request was created: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/486对于 ASP.NET Core,创建了以下拉取请求: 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干杯

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 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().在调用 app.UseSwaggerUI() 之后放置 app.UseMvc() 之前,我无法让它工作。

Asp Net Core > 2.2 in a RestFUL API, just set the default url in the Project/Properties/Debug settings在 RestFUL API 中 Asp Net Core > 2.2,只需在 Project/Properties/Debug 设置中设置默认 url

ASP Net Core >2.2 RestFUL API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM