Swagger UI for Web API

  

Scenario: Implement Swagger UI for Web API

Solution:

  1. Add Swashbuckle and Swashbuckle.Core Nuget packages
  2. SwaggerConfig.cs - Would be auto created. Sample file:
  3.  
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    using System.Web.Http;
    using MyCoreSolution;
    using Swashbuckle.Application;
    using Swashbuckle.Swagger.Annotations;
    using WebActivatorEx;
    
    [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
    
    namespace MyCoreSolution
    {
        /// <summary>
        /// </summary>
        public class SwaggerConfig
        {
            /// <summary>
            /// </summary>
            public static void Register()
            {
                var thisAssembly = typeof(SwaggerConfig).Assembly;
    
                GlobalConfiguration.Configuration
                    .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "My API 1.0");
                        c.PrettyPrint();
                        c.IgnoreObsoleteActions();
                        c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\XmlDoc\MyCoreSolution.xml");
                        c.SchemaFilter<ApplySwaggerSchemaFilterAttributes>();
                        c.UseFullTypeNameInSchemaIds();
                        c.IgnoreObsoleteProperties();
                        c.DescribeAllEnumsAsStrings();
    
                        //c.OperationFilter<>();
                    })
                    .EnableSwaggerUi(c =>
                    {
                        c.DisableValidator();
                        c.EnableDiscoveryUrlSelector();
                    });
            }
        }
    }
          3. Compile and publish the Web API. Navigate to uri [http://{api.endpoint}/swagger/ui/index] to 
              see swagger UI.
          4. To enable swagger to use XML comments
    • Go to Project properties -> "Build" tab -> Check XML Documentation file in output group.
    • The above file is provided in the above SwaggerConfig.cs -> IncludeXmlComments.        
          5. Decorate API Controller action methods with Swagger attributes.                  
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    using System;
    using System.Net;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Description;
    using System.Web.Http.Results;
    using Microsoft.AspNetCore.Mvc;
    using Swashbuckle.Swagger.Annotations;
    
    namespace Controllers
    {
        [RoutePrefix("root")]
        public class APIController : ApiController
        {
            public APIController()
            {
            }
    
            [HttpPost]
            [Route("data")]
            [ResponseType(typeof(string))]
            [SwaggerResponseRemoveDefaults]
            [SwaggerResponse(201, "Created", typeof(string))]
            [SwaggerResponse(400, "Bad Request", typeof(string))]
            [SwaggerResponse(409, "Validation Error", typeof(string))]
            public async Task<IHttpActionResult> PostData(string request)
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        //throw error
                    }
    
                    var data = "data";
    
                    return new NegotiatedContentResult<string>(
                        HttpStatusCode.Created,
                        data,
                        this);
                }
                catch (Exception e)
                {
                    throw;
                }
            }
    
            [HttpGet]
            [Route("data/events/{eventId}")]
            [ResponseType(typeof(string[]))]
            [SwaggerResponseRemoveDefaults]
            [SwaggerResponse(200, "OK", typeof(string[]))]
            [SwaggerResponse(400, "Bad Request", typeof(string))]
            [SwaggerResponse(409, "Validation Error", typeof(string))]
            public async Task<IHttpActionResult> GetData([FromUri] string eventId)
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        //throw error
                    }
    
                    var data = new string[] { "data" };
    
                    return new NegotiatedContentResult<string[]>(
                        HttpStatusCode.OK,
                        data,
                        this);
                }
                catch (Exception e)
                {
                    throw;
                }
            }
        }
    }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...