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.
Let’s set the XML documentation path and API document information for Swagger
.
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 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()
);
});
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)]
[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.
Here is another powerful function of Swagger Editor. You can choose to generate the document as HTML, codes… etc, as the reference.