问题
I'm building Asp.Net Core 2.x web api integrated with Swagger. To access the swagger, I had to append /swagger to the url, eg. https://mywebapi.azurewebsites.net/swagger/
How can I redirect https://mywebapi.azurewebsites.net/ to https://mywebapi.azurewebsites.net/swagger/ ?
回答1:
Install Microsoft.AspNetCore.Rewrite from Nuget
In Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
before
app.UseMvc();
add
var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");
app.UseRewriter(option);
回答2:
In Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
You should have section where you set Swagger UI options. Add and set the RoutePrefix option to an empty string.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My service");
c.RoutePrefix = string.Empty; // Set Swagger UI at apps root
});
回答3:
On Startup.cs, after:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
add :
options.RoutePrefix = string.Empty;
this will make your root url the main api url.
回答4:
Create a default controller like this:
using Microsoft.AspNetCore.Mvc;
namespace Api
{
[ApiExplorerSettings(IgnoreApi = true)]
public class DefaultController : Controller
{
[Route("/")]
[Route("/docs")]
[Route("/swagger")]
public IActionResult Index()
{
return new RedirectResult("~/swagger");
}
}
}
Any url "/", "/docs" or "/swagger" is redirect to "/swagger".
回答5:
- Open the launchSettings.json file.
- Under the "profiles" node depending on your setup you should have one or more profiles. In may case I had "IIS Express" and another with named with my project name (e.g WebApplication1 ), now changing the launchUrl entry to "launchUrl": "swagger" solved my problem.
- If this does not work and you have other profiles do the same and test.
回答6:
I have modified the launchSettings.json with "launchUrl": "swagger" instead of "launchUrl": "api/values"
work for me, if that doesnt work for you remove the c.RoutePrefix = string.Empty; from your app.UseSwaggerUI configuration.
来源:https://stackoverflow.com/questions/49290683/how-to-redirect-root-to-swagger-in-asp-net-core-2-x