[英]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.