Buscar contenidos

martes, 29 de enero de 2019

Adding Swagger to ASP.NET Core Web API using XML Documentation


https://exceptionnotfound.net/adding-swagger-to-asp-net-core-web-api-using-xml-documentation/


The Package

First, we need to grab the NuGet package for the project known as Swashbuckle.AspNetCore. This package adds Swagger, SwaggerUI, and other libraries to make it easy for us to create our API documentation.
With the package installed, we now need to enable our project to generate XML comments. The comments come from triple-slash (///) comments throughout our code.
First, in the project properties, check the box labeled "Generate XML Documentation".
Screenshot of the Project Properties page, with the Generate XML Documentation checkbox highlighted
You will probably also want to suppress warning 1591, which will now give warnings about any method, class, or field that doesn't have triple-slash comments.
Screenshot of the Project Properties page, with the Suppress Warnings box highlightes and warning 1591 added

Configuring Swagger

With the project now generating XML documentation, we need to make some changes to our Startup.cs file. Specifically, we need to enable the services layer to use Swagger and tell the app to use both Swagger and Swagger UI. Here's the code; details are immediately after.
public class Startup
{
    //...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //This line adds Swagger generation services to our container.
        services.AddSwaggerGen(c =>
        {
            //The generated Swagger JSON file will have these properties.
            c.SwaggerDoc("v1", new Info
            {
                Title = "Swagger XML Api Demo",
                Version = "v1",
            });
            
            //Locate the XML file being generated by ASP.NET...
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            
            //... and tell Swagger to use those XML comments.
            c.IncludeXmlComments(xmlPath);
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        //This line enables the app to use Swagger, with the configuration in the ConfigureServices method.
        app.UseSwagger();
        
        //This line enables Swagger UI, which provides us with a nice, simple UI with which we can view our API calls.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML Api Demo v1");
        });
    }
}

No hay comentarios:

Publicar un comentario