2016年12月19日 星期一

[ASP.NET Core X Angular](8) – Swagger for api document

 ASP.NET Core    Swagger    Swagger UI    Web api   API document


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.


Related articles

Environment

Visual Studio 2015 Update 3  
Microsoft.AspNetCore.Mvc 1.0.0
Swashbuckle.SwaggerGen 6.0.0-beta
Swashbuckle.SwaggerUi 6.0.0-beta


Implement



Install packages

Swashbuckle.SwaggerGen (6.0.0-beta902)
Swashbuckle.SwaggerUi (6.0.0-beta902)


Enable XML document output

Enable the XML documentation file option.




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");
            //var xmlPath = Configuration["Swagger:XmlPath"]; //Or set the path in appsettings.json 

            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 to Swagger UI

Run the Web api application and navigate to 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 link to 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'

PS.
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




沒有留言:

張貼留言