Add Swagger to existing .NET Core 2.0 API

In Startup.cs in ConfigureServices method after services.AddMvc(); add the following:

 

public IServiceProvider ConfigureServices(IServiceCollection services)
{
	services.AddSwaggerGen(c =>
	{
		c.SwaggerDoc("v1", new OpenApiInfo
		{
			Title = "My Api", 
			Version = "v1",
			Contact = new OpenApiContact()
			{
				Name = "Contact name",
				Email = "",
				Url = new Uri("http://www.something.com")
			}
		});
		// if you have schema conflicts this line will fix the error
		c.CustomSchemaIds(type => type.ToString());
	});
}

Then in Configure method after services.UserMvc(); add the following:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

	app.UseSwagger();
	app.UseSwaggerUI(c =>
	{
		c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
	});
}
Leave a reply