可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a WebApi project with Swashbuckle installed onto it.
In default setup, I must open in browser http://localhost:56131/swagger/ui/index
to view my operations description and test page. I want it to be accessible from root of the site: http://localhost:56131/
. How can I achieve this?
回答1:
Influenced by this answer to similar question, slightly modified code:
public class WebApiConfig
{
public static void Configure(IAppBuilder app)
{
var httpConfig = new HttpConfiguration();
// Attribute routing
config.MapHttpAttributeRoutes();
// Redirect root to Swagger UI
config.Routes.MapHttpRoute(
name: "Swagger UI",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new RedirectHandler(SwaggerDocsConfig.DefaultRootUrlResolver, "swagger/ui/index"));
// Configure OWIN with this WebApi HttpConfiguration
app.UseWebApi(httpConfig);
}
}
This way it is not necessary to create new WebAPI controller as so did @bsoulier in his answer.
This solution is based on already existing class RedirectHandler
in Swashbuckle.Core
assembly.
回答2:
If you for sure use a Web API project, you can:
- enable Http Attribute Routing,
- create the following method within an existing or new controller:
[Route(""), HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public HttpResponseMessage RedirectToSwaggerUi()
{
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found);
httpResponseMessage.Headers.Location = new Uri("/swagger/ui/index", UriKind.Relative);
return httpResponseMessage;
}
Note the use of ApiExplorerSettings
attribute, so that it doesn't show up in the Swagger definition.
回答3:
Even simpler variant of the above answer:
public class DefaultController : Controller
{
[Route(""), HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public RedirectResult RedirectToSwaggerUi()
{
return Redirect("/swagger/");
}
}
The simpler, the better! This one works for me.
回答4:
if the task allows you, in _layout.chtml just add follow line to head:
<meta http-equiv="refresh" content="0; URL='/swagger'" />
this will redirect you on swagger/index after page was loaded
回答5:
For .net core
in the properties launchsettings.json modify profiles and api sections to point to swagger.
profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"authapi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
回答6:
Change the value of launchUrl = "swagger/index.html"
in launchSetting.Json in asp.net core 2.1/2.2
"ProjectName": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger/index.html",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:44333"
}