Skip to main content

Add Swagger To Asp.Net Core Rest API

Brief

Add SwaggerGen to the services collection in the Configure method, and in the ConfigureServices method, enable the middleware for serving generated JSON document and the SwaggerUI.
  public void ConfigureServices(IServiceCollection services)
  {
      // Add framework services.
      services.AddMvc();

      services.AddLogging();

      // Add our repository type
      services.AddSingleton<ITodoRepository, TodoRepository>();

      // Inject an implementation of ISwaggerProvider with defaulted settings applied
      services.AddSwaggerGen();
  }

  // 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.UseMvcWithDefaultRoute();

      // Enable middleware to serve generated Swagger as a JSON endpoint
      app.UseSwagger();

      // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
      app.UseSwaggerUi();

  }
This document is used to drive the Swagger UI which can be viewed by navigating to http://localhost:<random_port>/swagger/ui

Links

Comments