How to Add Swagger interface on .NET Core Web API

This is an example for .NET Core Web API with .NET core 3.1 Framework.

  1. Add NSwag for NSwag.AspNetCore package from Nuget Package Manager.
  2. Add following information on the ConfigureServices() method on StartUp.cs file.
    This is the example of ConfigureServices method.

    Note: Put the code below ‘// Register the Swagger Services’ 

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    
        // Register the Swagger services
        services.AddSwaggerDocument();
    }
  3. Add following code inside of Configure Method.
    This is the example of Configure Method. (Line #10, #11 from following example)

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        // Register the Swagger generator and the Swagger UI middlewares
        app.UseOpenApi();
        app.UseSwaggerUi3();
    
        app.UseHttpsRedirection();
    
        app.UseRouting();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
  4. You can see the swagger interface with following URL.
    https://<your API Address>/swagger/index.html

Leave a Reply