0

Created new .net core 3.1 Web Api project and configured Swashbuckle to use swagger.

Everything works fine but I need my application use my own swagger spec file instead of auto-generated file(\swagger\v1\swagger.json)

I searched many posts like this but none of them help here.

I have created my-custom-swagger.json file in root path of project(same directory with .csproj)

Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseStaticFiles();
        app.UseSwagger();

    //    app.UseStaticFiles(new StaticFileOptions
    //{
    //    FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory),
    //    RequestPath = "my-custom-swagger.json"
    //    });

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core Test SW");
            c.RoutePrefix = string.Empty;
        });

How can I make swagger use my-custom-swagger.json file instead of auto-generated file

TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

3 Answers3

2

If you want to provide your own custom swagger/OpenAPI file for the swaggerUI, then here's what you need to do (code in c# .net5)

In ConfigureServices() add

   .AddSwaggerGen()

and .AddSwaggerGenNewtonsoftSupport() if you depend on Newtonsoft.Json serialization

In Configure add

    .UseSwagger()
    .UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/internal/swagger.json", "v1");
    })

Now we need to expose an endpoint with our custom file.

    .UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/internal/swagger.json", async context =>
        {
            await context.Response.WriteAsync(await File.ReadAllTextAsync("my-custom-swagger.json"));
        });
            
        // the rest of your code goes here
    });
wxt
  • 495
  • 1
  • 5
  • 12
0

I just run into this. I don't understand why is this so complicated when it should be quite straightforward.

Anyway, I solved it with this code in Startup.cs (.Net Core 5):

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddSwaggerGen();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Swagger")),
                RequestPath = "/CustomSwagger"
            });

            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/CustomSwagger/customswagger.json", "MySwagger"));
        }
    //...

Having the customswagger.json in rootSolutionFolder/Swagger, as it can be seen in the PhysicalFileProvider part, and mapping it to /CustomSwagger, so I can use it in the app.UseSwaggerUI part.

xecollons
  • 536
  • 6
  • 22
0

The easiest solution would be to place the swagger file in the wwwroot folder. You may need to create this folder since it is normally not part of a Web API.

Once the folder has been created, configure your startup process to use the StaticFiles middleware, this enables file browsing which means you can reach the file via HTTP, all you need to do then is to change the endpoint where the Swagger UI to loads the files.

For example, if I had a file in wwwroot/swagger/v1/swagger.json I would need to use the following code

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at 
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); 
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseStaticFiles();
app.UseSwagger();

// UI should use the path to the file location.
app.UseSwaggerUI(c=>c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1")); 
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

If dealing with YAML then you will need to use the FileExtensionContentTypeProvider as .NET only allows files with media types defined by the IANA group, but you can override this behavior with the following code.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at 
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
var provider = new FileExtensionContentTypeProvider();

// Add new mappings

// Allow YAML files to be served via HTTP request.
provider.Mappings[".yaml"] = "text/yaml"; 

app.UseStaticFiles(new StaticFileOptions
{
  ContentTypeProvider = provider
});

app.UseSwagger();
app.UseSwaggerUI(c=>c.SwaggerEndpoint("/swagger/v1/swagger.yaml", "v1"));
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
CircleUpX
  • 11
  • 2