How to redirect root to swagger in Asp.Net Core 2.x?

六眼飞鱼酱① 提交于 2019-12-18 19:40:55

问题


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:


  1. Open the launchSettings.json file.
  2. 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.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!