The Swagger Middleware is fully independent from the MVC pipeline, so it's not possible out of the box. However, with a bit of reverse engineering, I found a workaround. It involves re-implementing most of the middleware in a custom controller, so it's a bit involved, and obviously it can break with a future update.
First, we need to stop calling IApplicationBuilder.UseSwagger and IApplicationBuilder.UseSwaggerUI, so that it doesn't conflict with our controller.
Then, we must add everything that was added by those methods by modifying our Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("documentName", new Info { Title = "My API", Version = "v1" });
});
// RouteTemplate is no longer used (route will be set via the controller)
services.Configure<SwaggerOptions>(c =>
{
});
// RoutePrefix is no longer used (route will be set via the controller)
services.Configure<SwaggerUIOptions>(c =>
{
// matches our controller route
c.SwaggerEndpoint("/swagger/documentName/swagger.json", "My API V1");
});
}
public void Configure(IApplicationBuilder app)
{
// we need a custom static files provider for the Swagger CSS etc..
const string EmbeddedFileNamespace = "Swashbuckle.AspNetCore.SwaggerUI.node_modules.swagger_ui_dist";
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/swagger", // must match the swagger controller name
FileProvider = new EmbeddedFileProvider(typeof(SwaggerUIMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
});
}
Finally, there are two things to re-implement: the generation of the swagger.json file, and the generation of the swagger UI. We do this with a custom controller:
[Authorize]
[Route("[controller]")]
public class SwaggerController : ControllerBase
{
[HttpGet("{documentName}/swagger.json")]
public ActionResult<string> GetSwaggerJson([FromServices] ISwaggerProvider swaggerProvider,
[FromServices] IOptions<SwaggerOptions> swaggerOptions, [FromServices] IOptions<MvcJsonOptions> jsonOptions,
[FromRoute] string documentName)
{
// documentName is the name provided via the AddSwaggerGen(c => { c.SwaggerDoc("documentName") })
var swaggerDoc = swaggerProvider.GetSwagger(documentName);
// One last opportunity to modify the Swagger Document - this time with request context
var options = swaggerOptions.Value;
foreach (var filter in options.PreSerializeFilters)
{
filter(swaggerDoc, HttpContext.Request);
}
var swaggerSerializer = SwaggerSerializerFactory.Create(jsonOptions);
var jsonBuilder = new StringBuilder();
using (var writer = new StringWriter(jsonBuilder))
{
swaggerSerializer.Serialize(writer, swaggerDoc);
return Content(jsonBuilder.ToString(), "application/json");
}
}
[HttpGet]
[HttpGet("index.html")]
public ActionResult<string> GetSwagger([FromServices] ISwaggerProvider swaggerProvider, [FromServices] IOptions<SwaggerUIOptions> swaggerUiOptions)
{
var options = swaggerUiOptions.Value;
var serializer = CreateJsonSerializer();
var indexArguments = new Dictionary<string, string>()
{
{ "%(DocumentTitle)", options.DocumentTitle },
{ "%(HeadContent)", options.HeadContent },
{ "%(ConfigObject)", SerializeToJson(serializer, options.ConfigObject) },
{ "%(OAuthConfigObject)", SerializeToJson(serializer, options.OAuthConfigObject) }
};
using (var stream = options.IndexStream())
{
// Inject arguments before writing to response
var htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());
foreach (var entry in indexArguments)
{
htmlBuilder.Replace(entry.Key, entry.Value);
}
return Content(htmlBuilder.ToString(), "text/html;charset=utf-8");
}
}
private JsonSerializer CreateJsonSerializer()
{
return JsonSerializer.Create(new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new[] { new StringEnumConverter(true) },
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None,
StringEscapeHandling = StringEscapeHandling.EscapeHtml
});
}
private string SerializeToJson(JsonSerializer jsonSerializer, object obj)
{
var writer = new StringWriter();
jsonSerializer.Serialize(writer, obj);
return writer.ToString();
}
}