Given that the redirect you are applying here does not relate directly to ASP.NET Core MVC, one option is to Use Routing Middleware instead of adding the route within MVC itself. Here's an example:
app.UseRouter(builder =>
{
builder.MapGet("", context =>
{
context.Response.Redirect("./swagger/index.html", permanent: false);
return Task.FromResult(0);
});
});
The parameter passed into the UseRouter
delegate (builder
) is an instance of RouteBuilder
, which is the same type that is passed into the UseMvc
delegate. In the example above, we just apply the required route directly.
This call can be added either before or after your existing call to UseMvc
, but adding it before might be more logical (and maybe slightly more performant) seeing as the decision to redirect can be made without involving MVC.
It's worth noting that this approach doesn't use endpoint routing at all. In ASP.NET Core 2.2, Endpoint Routing only applies to ASP.NET Core MVC:
With the release of endpoint routing in ASP.NET Core 2.2, endpoint linking is limited to MVC/Razor Pages actions and pages. The expansions of endpoint-linking capabilities is planned for future releases.
Perhaps in the near future, this routing middleware approach will also change, but for now the approach I've provided works well and is fully supported.
As an alternative to using the routing middleware, it's also possible to use a simple custom middleware function to do the redirect. Here's an example of that for completeness:
app.Use(async (context, next) =>
{
if (context.Request.Path == "/")
{
context.Response.Redirect("./swagger/index.html", permanent: false);
return;
}
await next();
});
There are even more options for achieving this, but I won't enumerate them all here.
UseSwaggerUI(...)
. i.e.app.UseSwaggerUI(o => o.RoutePrefix = string.Empty);
. – SlipsheetUseSwaggerUI
since SwaggerUI updates were not frequent. Also, I have custom implementations in my swagger.js. Hence, I need custom routing :) – Incongruous