[英]How to use Swagger as Welcome Page of IAppBuilder in WebAPI
我尝试将Swagger与 Microsoft WebAPI 2 一起使用。
目前,我在一个方法中进行了以下调用。
appBuilder
.ConfigureOAuth()
.UseWebApi(configuration)
.UseWelcomePage();
如果我想使用 Swagger,我必须使用这个 url “ https://localhost:44300/swagger ”,它非常有效。
我希望我的主页重定向到我 swagger 的 url,可能如下所示,但此示例不起作用。
appBuilder
...
.UseWelcomePage("/swagger");
任何的想法 ?
我通过在 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 }
);
}
从 swashbuckle 查看此代码以了解发生了什么: https : //github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Application/RedirectHandler.cs
在 Configuration(IAppBuilder app) 方法的 Startup.cs 文件中,我使用这行代码使其在加载时重定向到 swagger 欢迎页面。
app.Run(async context => {
context.Response.Redirect("swagger/ui/index");
});
所以我使用的完整方法如下
[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");
});
}
}
}
请注意,这将导致 Visual Studio 中出现绿色警告。 我确信有一些方法可以通过函数中的 await 调用将其模拟为异步。
对于 Asp.Net 核心使用这个:
app.Run(context => {
context.Response.Redirect("swagger/ui");
return Task.CompletedTask;
});
好的,这是一种方法。 添加一个新的 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");
}
}
}
另外,请确保您的路由配置具有以下内容(注意,默认情况下它已经这样做了)
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 }
);
}
如果您来这里寻找 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
});
在 ASP.NET Core 中,您可以在将 SwaggerUI 注册为空字符串时简单地更改 RoutePrefix。
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "";
...
};
不需要重定向配置,除非您仍然需要/swagger
或路径中的类似内容。
我有类似的问题,我通过自定义 SwaggerUI url 解决了它。 这是我的配置方法:
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";
}
这样,当您转到localhost:44300
您将获得 Swagger UI 作为启动页面。
您可以做什么,只需将 Home Controller & Index Action 设置为您的默认值,然后修改您的控制器操作,如下所示:
public class HomeController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return new RedirectResult("~/swagger");
}
}
这个问题的简短而快速的解决方案。
您可以在配置对象中设置一些路由。 由于您的代码段很有限,因此很难说出全部细节。 希望这能为您指明正确的方向。
在 .Net Core 中,只需打开应用程序的 Properties,转到 Debug 选项卡,然后在“Launch browser”文本框中写入 Swagger,
对于 ASP.NET Core,创建了以下拉取请求: https : //github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/486
同时,可以使用以下解决方法:
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;
}
干杯
遵循此处的示例:
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
}
}
在调用 app.UseSwaggerUI() 之后放置 app.UseMvc() 之前,我无法让它工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.