Add Swagger to your .NET Core Web API

Add Swagger to your .NET Core Web API

Last week .NET Core was released, and the first thing I tried to solve was how to Add Swagger to your .NET Core Web API:

Dependencies


At the time of writing you should add the following dependency to your project.json file

    "Swashbuckle": "6.0.0-beta901"

Using statement


In your Startup class add the following using statement

    using Swashbuckle.Swagger.Model;

Add Swagger as a service


In your Startup class add the following code to the ConfigureServices method

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
       ...

       services.AddSwaggerGen();
       services.ConfigureSwaggerGen(options =>
       {
           options.SingleApiVersion(new Info
           {
               Version = "v1",
               Title = "Your API title here",
               Description = "Your API description here",
               TermsOfService = "Your API terms of service here"
           });
       });
    }

Add Swagger to the HTTP request pipeline


And finally add the following lines to the Configure method of your Startup class

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...

        app.UseSwagger();
        app.UseSwaggerUi();
    }

And that’s it you are ready to go!

Hope it helps!

Last modified December 12, 2024: new post (bf52b37)