ASP.NET Core Web API configuration with Swagger


Note: some times if any exception occurs in controller (failed to load specification) then need to check api with Postman because swagger can not show the specific exception details.


What is Swagger?
Swagger is an open source, human and machine readable API framework to design, build, and document.APIs. What this means is that Swagger defines an API’s RESTful contract, allowing all the API’s stakeholders,be it your development team, or your end consumers, to understand what the API does and interact with its various resources, without having to integrate it into their own application.
Swagger is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a service without any direct access to the implementation (source code, network access, documentation). One goal is to minimize the amount of work needed to connect disassociated services. Another goal is to reduce the amount of time needed to accurately document a service.
The importance of API documentation:
A survey by Programmable Web found that API consumers considered complete and accurate documentation as the biggest factor that figured in their API decision making, even outweighing price and API performance. Good documentation accelerates development and consumption, and reduces the money and time that would otherwise be spent answering support calls. Documentation is part of the overall user experience, and is one of the biggest factors for increased API growth and usage
Swagger configuration with Asp.Net Core API

NuGet Packages:
Install the below NuGet package
Install-Package Swashbuckle.AspNetCore.Swagger
Install-Package Swashbuckle.AspNetCore.SwaggerGen
Install-Package Swashbuckle.AspNetCore.SwaggerUI

Configure Swagger in the Startup.cs
Add the Swagger generator to the service collection after services.AddMvc();
Enable the middleware for serving the generated JSON document after app.UseStaticFiles();

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMvc(options =>
            {
                options.InputFormatters.Add(new XmlSerializerInputFormatter());
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            });

            //Swagger Configuration
            services.ConfigureSwaggerGen(options =>
            {
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine("./wwwroot/XmlDocument/", xmlFile);
                if (!string.IsNullOrEmpty(xmlPath))
                    options.IncludeXmlComments(xmlPath);
                options.DescribeAllEnumsAsStrings();

            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Test", Version = "v1" });
            });
     

    }

        // 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.UseCors(builder =>
                                    builder.WithOrigins("*")
                                    .AllowAnyOrigin()
                                    .AllowAnyMethod()
                                    .AllowAnyHeader()
                                    .AllowCredentials());
            app.UseStaticFiles(); // For the wwwroot folder         
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            //Custom Swagger ui setting
            app.UseSwaggerUI(o =>
            {
               o.SwaggerEndpoint("../swagger/v1/swagger.json", "test");
                o.InjectStylesheet("../css/Swagger-ui.css");
            });
            //swagger default url setting
           var option = new RewriteOptions();
           option.AddRedirect("^$", "swagger");
          app.UseRewriter(option);
            app.UseMvc();
     
    }




Configure  XML path file and logo image file.
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

    <DocumentationFile>wwwroot\XmlDocument\ProjectName.xml</DocumentationFile>
  </PropertyGroup>

Note: make sure css file,xml file and image file should be as resource files.
Open file property->Build Action  and set Embedded resource.
Change in launchsettings file :  "launchUrl": "swagger" for both profile and project.




Comments

Popular posts from this blog

Asp .Net Core

Microsoft Enterprise Library-Data Access Application Block for for .Net Core & .Net Standard

Asp .Net Core -Startup Class and the Service Configuration