Install-Package Swashbuckle -Pre
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddLogging(); // Add our repository type services.AddSingleton<ITodoRepository, TodoRepository>(); // Inject an implementation of ISwaggerProvider with defaulted settings applied services.AddSwaggerGen(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
http://localhost:<random_port>/swagger/v1/swagger.json
. Here you will see the created document describing the end points.
{ "swagger": "2.0", "info": { "version": "v1", "title": "API V1" }, "basePath": "/", "paths": { "/api/Todo": { "get": { "tags": [ "Todo" ], "operationId": "ApiTodoGet", "consumes": [], "produces": [ "text/plain", "application/json", "text/json" ], "responses": { "200": { "description": "OK", "schema": { "type": "array", "items": { "$ref": "#/definitions/TodoItem" } } } }, "deprecated": false }, "post": { ... } }, "/api/Todo/{id}": { "get": { ... }, "put": { ... }, "delete": { ... }, "definitions": { "TodoItem": { "type": "object", "properties": { "key": { "type": "string" }, "name": { "type": "string" }, "isComplete": { "type": "boolean" } } } }, "securityDefinitions": {} }
http://localhost:<random_port>/swagger/ui
.
ConfigureSwaggerGen
method is intended to add information about the author and license, as well as descriptions.
services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"}, License = new License { Name = "Use under LICX", Url = "http://url.com" } }); });
ToDoApi.XML
is possible in Windows, but not in CentOS.
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddLogging(); // Add our repository type. services.AddSingleton<ITodoRepository, TodoRepository>(); // Inject an implementation of ISwaggerProvider with defaulted settings applied. services.AddSwaggerGen(); // Add the detail information for the API. services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"}, License = new License { Name = "Use under LICX", Url = "http://url.com" } }); //Determine base path for the application. var basePath = PlatformServices.Default.Application.ApplicationBasePath; //Set the comments path for the swagger json and ui. var xmlPath = Path.Combine(basePath, "TodoApi.xml"); options.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
TodoApi.xml
works only in this example, the name of the created XML file with comments is assigned based on the name of the application.
/// <summary> /// Deletes a specific TodoItem. /// </summary> /// <param name="id"></param> [HttpDelete("{id}")] public void Delete(string id) { TodoItems.Remove(id); }
"delete": { "tags": [ "Todo" ], "summary": "Deletes a specific TodoItem", "operationId": "ApiTodoByIdDelete", "consumes": [], "produces": [], "parameters": [ { "name": "id", "in": "path", "description": "", "required": true, "type": "string" } ], "responses": { "204": { "description": "No Content" } }, "deprecated": false }
<remarks />
, the contents of which can be text, a JSON object or XML for further documentation of the method.
/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Note that the key is a GUID and not an integer. /// /// POST /Todo /// { /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>New Created Todo Item</returns> /// <response code="201">Returns the newly created item</response> /// <response code="400">If the item is null</response> [HttpPost] [ProducesResponseType(typeof(TodoItem), 201)] [ProducesResponseType(typeof(TodoItem), 400)] public IActionResult Create([FromBody, Required] TodoItem item) { if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { id = item.Key }, item); }
System.ComponentModel.DataAnnotations
controller to enhance the elements of the Swagger user interface.
[Required]
annotation to the Name
property of the TodoItem
class changes the ModelSchema information in the user interface. Check agents [Produces("application/json")]
, RegularExpression
and other functions serve to refine the information displayed on the page being created. The more metadata used in the code, the more informative the user interface or API reference page becomes.
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace TodoApi.Models { public class TodoItem { public string Key { get; set; } [Required] public string Name { get; set; } [DefaultValue(false)] public bool IsComplete { get; set; } } }
Create()
method. By default, it issues the response “201 Created” (if the item is actually created) or “204 No Content” (if no data is sent to the POST body). However, there is no documentation that tells you what the answer will be. To remedy this, add the following code snippet.
/// <summary> /// Creates a TodoItem. /// </summary> /// <remarks> /// Note that the key is a GUID and not an integer. /// /// POST /Todo /// { /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", /// "name": "Item1", /// "isComplete": true /// } /// /// </remarks> /// <param name="item"></param> /// <returns>New Created Todo Item</returns> /// <response code="201">Returns the newly created item</response> /// <response code="400">If the item is null</response> [HttpPost] [ProducesResponseType(typeof(TodoItem), 201)] [ProducesResponseType(typeof(TodoItem), 400)] public IActionResult Create([FromBody, Required] TodoItem item) { if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { id = item.Key }, item); }
«Microsoft.AspNetCore.StaticFiles»: «1.0.0-*»
package to the project «Microsoft.AspNetCore.StaticFiles»: «1.0.0-*»
.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Enable static files middleware. app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); }
<https://github.com/domaindrivendev/Ahoy/tree/master/test/WebSites/CustomizedUi/wwwroot/swagger/ui>
_ and move it in the wwwroot/swagger/ui
folder, then create a new custom.css
file in the same folder.
<link href='custom.css' media='screen' rel='stylesheet' type='text/css' />
.swagger-section #header { border-bottom: 1px solid #000000; font-style: normal; font-weight: 400; font-family: "Segoe UI Light","Segoe WP Light","Segoe UI","Segoe WP",Tahoma,Arial,sans-serif; background-color: black; } .swagger-section #header h1 { text-align: center; font-size: 20px; color: white; }</code> <i> index.html</i> <source lang="css"><body class="swagger-section"> <div id="header"> <h1>ToDo API Documentation</h1> </div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div> <div id="swagger-ui-container" class="swagger-ui-wrap"></div> </body>
Source: https://habr.com/ru/post/325872/