问题
I try to use Swagger with 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.
I want my home page redirects to the url of my swagger, perhaps as follows but this sample doesn't works.
appBuilder
...
.UseWelcomePage("/swagger");
Any idea ?
回答1:
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
回答2:
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.
回答3:
For Asp.Net core use this:
app.Run(context => {
context.Response.Redirect("swagger/ui");
return Task.CompletedTask;
});
回答4:
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 }
);
}
回答5:
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.
回答6:
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?
回答7:
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.
回答8:
In .Net Core, just open Properties of the application, go to Debug tab, and write Swagger in the "Launch browser" text box,
launch browser
回答9:
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.
回答10:
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.
回答11:
Asp Net Core > 2.2 in a RestFUL API, just set the default url in the Project/Properties/Debug settings
回答12:
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
回答13:
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().
来源:https://stackoverflow.com/questions/30028736/how-to-use-swagger-as-welcome-page-of-iappbuilder-in-webapi