iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 4
0
Modern Web

Learning ASP.NET core + Angular2 系列 第 4

[ASP.NET Core] Swagger for RESTful api document

  • 分享至 

  • xImage
  •  

Introduction


Swagger is a powerful open source framework that helps you design, build, document the RESTful APIs. We are going to install Swagger into our web api and create the api document.

Environment


  • Visual Studio 2015 Update 3
  • dotnet 1.0.0-preview2-003131
  • Swashbuckle.SwaggerGen 6.0.0-beta
  • Swashbuckle.SwaggerUi 6.0.0-beta

Walk thru


Install packages

Enable XML document output

Configuration

Let’s set the XML documentation path and API document information for Swagger.

  • Startup.cs
public void ConfigureServices(IServiceCollection services)
{
        #region MVC
        //...
        #endregion
        #region CORS
        //...
        #endregion

        #region Swagger
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var xmlPath = Path.Combine(basePath, "Angular2.Mvc.Webapi.xml");
        services.AddSwaggerGen();
        services.ConfigureSwaggerGen(options =>
         {
                options.SingleApiVersion(new Swashbuckle.Swagger.Model.Info
                {
                    Version = "v1",
                    Title = "Angular2.Mvc WebApi",
                    Description = "Angular2.Mvc WebApi samples",
                    TermsOfService = "None"
                });
                options.IncludeXmlComments(xmlPath);
                options.DescribeAllEnumsAsStrings();
          });

        #endregion
}

Run Web api and navigate Swagger UI

Run the Web api application and navigate the URL :
http://localhost:XXXX/swagger/ui/index.html

Okay, now we get the api document, let’s try use the Swagger Editor to modify the document.
Copy the url on the top of the document and browse it, you will get a JSON on the browser.

Copy the JSON.

Go to Swagger Editor and import the JSON as file or just paste it.

Okay we put our api document on the Swagger Editor, now we can edit the document!
For example, we add the host url for testing the APIs.

host: 'localhost:xxxx'

If you encounter the problem of COR from Swagger Editor.
Just add the CORS support for Swagger Editor.

    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
           builder =>
           builder.WithOrigins("http://localhost:4240", "http://editor.swagger.io") 
                 .WithMethods("HEAD", "GET", "POST", "PUT", "DELETE") //Or AllowAnyMethod()
         );
    });

Produces Different Response Type

Swagger also support the different response type on the document.
Here is a sample, the Web api method returns DtoError object when there is an InternalServer error(500).

All we have to do the add this line:
[ProducesResponseType(typeof(DtoError), 500)]

  • ApiController
    [HttpGet("GetAll")]
    [ProducesResponseType(typeof(DtoError), 500)] 
    public IQueryable<DtoCustomer> GetAll()
    {
       try
       {}
       catch (Exception ex)
       {
                var err = new DtoError
                {
                    StatusCode = 500,
                    ServerError = ex.Message,
                    ClientMsg = "Please try again..."
                };

                var errJson = JsonConvert.SerializeObject(err);
                byte[] data = System.Text.Encoding.UTF8.GetBytes(errJson);
                Response.ContentType = "application/json";
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                Response.Body.WriteAsync(data, 0, data.Length);
                throw;
      }

    }

And the API document will be updated like this.

Generate Client

Here is another powerful function of Swagger Editor. You can choose to generate the document as HTML, codes… etc, as the reference.

Reference


  1. ASP.NET CORE 1.0 MVC API DOCUMENTATION USING SWASHBUCKLE SWAGGER
  2. Swagger

上一篇
[Entity Framework core] CLI migrations
下一篇
[ASP.NET Core X Angular2] NOT A Hello world
系列文
Learning ASP.NET core + Angular2 31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言