24

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/ ?

Syaiful Nizam Yahya
  • 3,694
  • 11
  • 42
  • 65

6 Answers6

33

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);
Syaiful Nizam Yahya
  • 3,694
  • 11
  • 42
  • 65
27

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
            });
Dmitriy B
  • 270
  • 3
  • 4
  • 2
    this is setting a route prefix to the swagger, rather than redirecting to the actual swagger root. You actually have to change in launchSettings.json -> launchUrl – nkalfov Dec 11 '18 at 14:38
8

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".

George Paoli
  • 1,615
  • 1
  • 19
  • 25
6

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.

ArlanG
  • 415
  • 5
  • 10
  • In Properties folder, if I didn't set in launchSettings.json under "profiles" "launchUrl" values to "" (empty string) this above didn't work for me. Now I have this - "launchUrl": "" and it works. – SushiDynamite Aug 04 '20 at 08:50
1
  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.
Mxaza
  • 319
  • 3
  • 9
1

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.