diff --git a/.gitignore b/.gitignore index 5784b766fd9f..9ee34283f9e2 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,7 @@ _build/ *.user *.userosscache *.sln.docstates - +*.vscode/ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs diff --git a/aspnet/ext/versionwarning.pyc b/aspnet/ext/versionwarning.pyc new file mode 100644 index 000000000000..6abe70d57f2d Binary files /dev/null and b/aspnet/ext/versionwarning.pyc differ diff --git a/aspnet/tutorials/index.rst b/aspnet/tutorials/index.rst index 96cb8d4fc3b7..bfaa0a335590 100644 --- a/aspnet/tutorials/index.rst +++ b/aspnet/tutorials/index.rst @@ -12,3 +12,4 @@ Tutorials ASP.NET Core and Azure Service Fabric /mobile/native-mobile-backend dotnet-watch + web-api-help-pages-using-swagger diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger.rst b/aspnet/tutorials/web-api-help-pages-using-swagger.rst new file mode 100644 index 000000000000..49e3ec88e637 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger.rst @@ -0,0 +1,377 @@ +.. _web-api-help-pages-using-swagger: + +ASP.NET Web API Help Pages using Swagger +======================================== + +By `Shayne Boyer`_ + +Understanding the various methods of an API can be a challenge for a developer when building a consuming application. + +Generating good documentation and help pages as a part of your Web API using `Swagger `_ with the .NET Core implementation `Swashbuckle `_ is as easy as adding a couple of NuGet packages and modifying the *Startup.cs*. + +- `Swashbuckle `_ is an open source project for generating Swagger documents for Web APIs and built with ASP.NET Core MVC. + +- `Swagger `_ is a machine readable representation of a RESTful API that enables support for interactive documentation, client SDK generation and discoverability. + +This tutorial builds on the sample on :doc:`first-web-api`. If you'd like to follow along, download the sample at https://github.com/aspnet/Docs/tree/master/aspnet/tutorials/first-web-api/sample. + +.. contents:: Sections: + :local: + :depth: 2 + +Getting Started +--------------- +There are two core components to Swashbuckle + +- *Swashbuckle.SwaggerGen* : provides the functionality to scaffold your Web API and generate JSON Swagger documents that describe the objects, methods, return types, etc. +- *Swashbuckle.SwaggerUI* : an embedded version of the Swagger UI tool which uses the above documents for a rich customizable experience for describing the Web API functionality and includes built in test harness capabilities for the public methods. + +NuGet Packages +-------------- +You can add Swashbuckle with any of the following approaches: + +- From the Package Manager Console: + +.. code-block:: bash + + Install-Package Swashbuckle -Pre + +- Add Swashbuckle to *project.json*: + +.. code-block:: javascript + + "Swashbuckle": "6.0.0-*" + +- In Visual Studio: + - Right click your project in Solution Explorer > Manage NuGet Packages + - Enter Swashbuckle in the search box + - Check "Include prerelease" + - Set the Package source to nuget.org + - Tap the Swashbuckle package and then tap Install + + + +Add and configure Swagger to the middleware +------------------------------------------- + +Add SwaggerGen to the services collection in the Configure method, and in the ConfigureServices method, enable the middleware for serving generated JSON document and the SwaggerUI. + +.. code-block:: c# + :emphasize-lines: 12,21,24 + + public void ConfigureServices(IServiceCollection services) + { + // Add framework services. + services.AddMvc(); + + services.AddLogging(); + + // Add our repository type + services.AddSingleton(); + + // 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(); + + } + + +In Visual Studio, press ^F5 to launch the app and navigate to ``http://localhost:/swagger/v1/swagger.json`` to see the document generated that describes the endpoints. + +.. note:: Microsoft Edge, Google Chrome and Firefox display JSON documents natively. There are extensions for Chrome that will format the document for easier reading. *Example below reduced for brevity.* + +.. code-block:: javascript + + { + "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": {} + } + +This document is used to drive the Swagger UI which can be viewed by navigating to ``http://localhost:/swagger/ui`` + +.. image:: web-api-help-pages-using-swagger/_static/swagger-ui.png + +Each of the methods in the ToDo controller can be tested from the UI. Tap a method to expand the section, add any necessary parameters and tap "Try it out!". + +.. image:: web-api-help-pages-using-swagger/_static/get-try-it-out.png + + +Customization & Extensibility +----------------------------- +Swagger is not only a simple way to represent the API, but has options for documenting the object model, as well as customizing the interactive UI to match your look and feel or design language. + +API Info and Description +'''''''''''''''''''''''' +The ``ConfigureSwaggerGen`` method can be used to add information such as the author, license, description. + +.. code-block:: c# + + 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" } + }); + }); + +The following image shows the Swagger UI displaying the version information added. + +.. image:: web-api-help-pages-using-swagger/_static/custom-info.png + +XML Comments +''''''''''''' +To enable XML comments, right click the project in Visual Studio and select **Properties** and then check the **XML Documentation file** box under the **Output Settings** section. + +.. image:: web-api-help-pages-using-swagger/_static/swagger-xml-comments.png + :scale: 75% + +Alternatively, you can enable XML comments by setting `"xmlDoc": true` in *project.json*. + +.. code-block:: javascript + :emphasize-lines: 4 + + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true + }, + +Configure Swagger to use the generated XML file. + +.. note:: For Linux or non-Windows operating systems, file names and paths can be case sensitive. So ``ToDoApi.XML`` would be found on Windows but not CentOS for example. + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/Startup.cs + :language: c# + :start-after: snippet_Configure + :end-before: #endregion + :dedent: 8 + :emphasize-lines: 29,32 + +In the code above, ApplicationBasePath gets the base path of the app, which is needed to set the full path to the XML comments. ``TodoApi.xml`` only works for this example, the name of the generated XML comments file is based on the name of your application. + +Adding the triple slash comments to the method enhances the Swagger UI by adding the description to the header of the section. + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs + :language: c# + :start-after: Delete_Method + :end-before: #endregion + :dedent: 8 + :emphasize-lines: 2 + +.. image:: web-api-help-pages-using-swagger/_static/triple-slash-comments.png + +Note that the UI is driven by the generated JSON file, and these comments are also in that file as well. + +.. code-block:: javascript + :emphasize-lines: 5 + + "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 + } + +Here is a more robust example, adding ```` where the content can be just text or adding the JSON or XML object for further documentation of the method. + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs + :language: c# + :start-after: Create_Method + :end-before: #endregion + :dedent: 8 + :emphasize-lines: 4-14 + +Notice the enhancement of the UI with these additional comments. + +.. image:: web-api-help-pages-using-swagger/_static/xml-comments-extended.png + + +DataAnnotations +''''''''''''''' +You can decorate the API controller with ``System.ComponentModel.DataAnnotations`` to help drive the Swagger UI components. + +Adding the ``[Required]`` annotation to the ``Name`` property of the TodoItem class will change the ModelSchema information in the UI. ``[Produces("application/json"]``, RegularExpression validators and more will further detail the information delivered in the generated page. The more metadata that is in the code produces a more desciptive UI or API help page. + + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoItem.cs + :language: c# + :emphasize-lines: 10 + + +Describing Response Types +''''''''''''''''''''''''' +Consuming developers are probably most concerned with what is returned; specifically response types, error codes (if not standard). These are handled in the XML comments and DataAnnotations. + +Take the ``Create()`` method for example, currently it returns only "201 Created" response by default. That is of course if the item is in fact created, or a "204 No Content" if no data is passed in the POST Body. However, there is no documentation to know that or any other response. That can be fixed by adding the following piece of code. + + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs + :language: c# + :start-after: Create_Method + :end-before: #endregion + :dedent: 8 + :emphasize-lines: 17,18,20,21 + +.. image:: web-api-help-pages-using-swagger/_static/data-annotations-response-types.png + +Customizing the UI +'''''''''''''''''' +The stock UI is very functional as well as presentable, however when building documentation pages for your API you want it to represent your brand or look and feel. + +Accomplishing that task with the Swashbuckle components is simple but requires adding the resources to serve static files that would not normally be included in a Web API project and then building the folder structure to host those files. + +Add the ``"Microsoft.AspNetCore.StaticFiles": "1.0.0-*"`` NuGet package to the project. + +Enable static files middleware. + +.. code-block:: c# + :emphasize-lines: 4 + + // 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(); + + } + +Acquire the core *index.html* file used for the Swagger UI page from the `Github repository `_ and put that in the ``wwwroot/swagger/ui`` folder and also create a new ``custom.css`` file in the same folder. + +.. image:: web-api-help-pages-using-swagger/_static/custom-files-folder-view.png + :scale: 80% + +Reference *custom.css* in the *index.html* file. + +.. code-block:: html + + + +The following CSS provides a simple sample of a custom header title to the page. + +*custom.css file* + +.. literalinclude:: web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/custom.css + :language: css + +*index.html body* + +.. code-block:: html + + + + +
 
+
+ + + +.. image:: web-api-help-pages-using-swagger/_static/custom-header.png + +There is much more you can do with the page, see the full capabilities for the UI resources at the `Swagger UI Github repository
`_. + + + diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/.DS_Store b/aspnet/tutorials/web-api-help-pages-using-swagger/.DS_Store new file mode 100644 index 000000000000..f1aa20e186dc Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/.DS_Store differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/add-swagger.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/add-swagger.png new file mode 100644 index 000000000000..61a8289ade78 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/add-swagger.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/basic-no-annotations.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/basic-no-annotations.png new file mode 100644 index 000000000000..f2e9ff574760 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/basic-no-annotations.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-files-folder-view.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-files-folder-view.png new file mode 100644 index 000000000000..6649e8c1da2b Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-files-folder-view.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-header.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-header.png new file mode 100644 index 000000000000..7fe8f2c58092 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-header.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-info.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-info.png new file mode 100644 index 000000000000..885808c0e3ec Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/custom-info.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations-response-types.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations-response-types.png new file mode 100644 index 000000000000..6cd6aefef59d Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations-response-types.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations.png new file mode 100644 index 000000000000..610e133f4dda Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/data-annotations.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/get-try-it-out.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/get-try-it-out.png new file mode 100644 index 000000000000..11550c9ac291 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/get-try-it-out.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/manage-nuget-packages.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/manage-nuget-packages.png new file mode 100644 index 000000000000..c9ce90e6d594 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/manage-nuget-packages.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-ui.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-ui.png new file mode 100644 index 000000000000..1c3957b71cdd Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-ui.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-xml-comments.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-xml-comments.png new file mode 100644 index 000000000000..ee7ce8bdef41 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/swagger-xml-comments.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/triple-slash-comments.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/triple-slash-comments.png new file mode 100644 index 000000000000..9519d29172e0 Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/triple-slash-comments.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/_static/xml-comments-extended.png b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/xml-comments-extended.png new file mode 100644 index 000000000000..669c2d4aaf0c Binary files /dev/null and b/aspnet/tutorials/web-api-help-pages-using-swagger/_static/xml-comments-extended.png differ diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs new file mode 100644 index 000000000000..cb7a967b9e10 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Controllers/TodoController.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using TodoApi.Models; +using System.ComponentModel.DataAnnotations; +using System.Net; +using Swashbuckle.SwaggerGen.Annotations; + +namespace TodoApi.Controllers +{ + /// + /// API Controller for Todo Items + /// + [Produces("application/json")] + [Route("api/[controller]")] + public class TodoController : Controller + { + /// + /// Constructor + /// + /// + public TodoController(ITodoRepository todoItems) + { + TodoItems = todoItems; + } + + /// + /// repository for Todo items + /// + public ITodoRepository TodoItems { get; set; } + + /// + /// returns a collection of TodoItems. + /// + /// + [HttpGet] + [Produces("application/json", Type = typeof(IEnumerable))] + public IEnumerable GetAll() + { + return TodoItems.GetAll(); + } + + /// + /// Returns a specific TodoItem. + /// + /// + /// + [Produces("application/json", Type = typeof(TodoItem))] + [HttpGet("{id}", Name = "GetTodo")] + public IActionResult GetById(string id) + { + var item = TodoItems.Find(id); + if (item == null) + { + return NotFound(); + } + return new ObjectResult(item); + } + #region Create_Method + /// + /// Creates a TodoItem. + /// + /// + /// Note that the key is a GUID and not an integer. + /// + /// POST /Todo + /// { + /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", + /// "name": "Item1", + /// "isComplete": true + /// } + /// + /// + /// + /// New Created Todo Item + /// Todo Item created + /// Todo Item invalid + [HttpPost] + [SwaggerResponse(HttpStatusCode.Created, "Returns the newly created Todo item.", typeof(TodoItem))] + [SwaggerResponse(HttpStatusCode.BadRequest, "If the item is null", typeof(TodoItem))] + public IActionResult Create([FromBody, Required] TodoItem item) + { + if (item == null) + { + return BadRequest(); + } + TodoItems.Add(item); + return CreatedAtRoute("GetTodo", new { id = item.Key }, item); + } + #endregion + /// + /// Updates a specific TodoItem. + /// + /// + /// This is just some additional information that you can put in regarding the method. + /// + /// + /// + /// + [HttpPut("{id}")] + public IActionResult Update(string id, [FromBody] TodoItem item) + { + if (item == null || item.Key != id) + { + return BadRequest(); + } + + var todo = TodoItems.Find(id); + if (todo == null) + { + return NotFound(); + } + + TodoItems.Update(item); + + return new NoContentResult(); + } + #region Delete_Method + /// + /// Deletes a specific TodoItem. + /// + /// + [HttpDelete("{id}")] + public void Delete(string id) + { + TodoItems.Remove(id); + } + #endregion + } +} diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/ITodoRepository.cs b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/ITodoRepository.cs new file mode 100644 index 000000000000..cec39ea6f07b --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/ITodoRepository.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; + +namespace TodoApi.Models +{ + public interface ITodoRepository + { + void Add(TodoItem item); + IEnumerable GetAll(); + TodoItem Find(string key); + TodoItem Remove(string key); + void Update(TodoItem item); + } +} \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoItem.cs b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoItem.cs new file mode 100644 index 000000000000..cdcea0fdb18b --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoItem.cs @@ -0,0 +1,15 @@ +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; } + } +} \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoRepository.cs b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoRepository.cs new file mode 100644 index 000000000000..b9096d0d9bfc --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Models/TodoRepository.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Collections.Concurrent; + +namespace TodoApi.Models +{ + public class TodoRepository : ITodoRepository + { + private static ConcurrentDictionary _todos = + new ConcurrentDictionary(); + + public TodoRepository() + { + Add(new TodoItem { Name = "Item1" }); + } + + public IEnumerable GetAll() + { + return _todos.Values; + } + + public void Add(TodoItem item) + { + item.Key = Guid.NewGuid().ToString(); + _todos[item.Key] = item; + } + + public TodoItem Find(string key) + { + TodoItem item; + _todos.TryGetValue(key, out item); + return item; + } + + public TodoItem Remove(string key) + { + TodoItem item; + _todos.TryGetValue(key, out item); + _todos.TryRemove(key, out item); + return item; + } + + public void Update(TodoItem item) + { + _todos[item.Key] = item; + } + } +} \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Properties/launchSettings.json b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Properties/launchSettings.json new file mode 100644 index 000000000000..33b83c3557b6 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:1385/", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/todo", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "TodoApi": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "http://localhost:5000/api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Startup.cs b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Startup.cs new file mode 100644 index 000000000000..7237294fe31b --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/Startup.cs @@ -0,0 +1,80 @@ +using System.IO; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using TodoApi.Models; +using Swashbuckle.Swagger.Model; +using Microsoft.Extensions.PlatformAbstractions; + +namespace TodoApi +{ + public class Startup + { + + #region snippet_Configure + // 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(); + + // 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. + options.IncludeXmlComments(basePath + "\\TodoApi.xml"); + }); + } + + // 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(); + + } + #endregion + + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup() + .UseKestrel() + .UseIISIntegration() + .Build(); + + host.Run(); + } + } +} diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/TodoApi.xproj b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/TodoApi.xproj new file mode 100644 index 000000000000..828b21f8d76a --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/TodoApi.xproj @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + fbb39b41-d165-4975-8f08-eeb5541662e8 + TodoApi + .\obj + .\bin\ + + + + 2.0 + + + \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/project.json b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/project.json new file mode 100644 index 000000000000..58dd614f7e84 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/project.json @@ -0,0 +1,53 @@ +{ + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true + }, + "dependencies": { + "Microsoft.AspNetCore.Hosting": "1.0.0-*", + "Microsoft.AspNetCore.Mvc": "1.0.0-*", + "Microsoft.AspNetCore.Mvc.Core": "1.0.0-*", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", + "Microsoft.Extensions.Logging.Console": "1.0.0-*", + "Swashbuckle": "6.0.0-beta901", + "Microsoft.AspNetCore.StaticFiles": "1.0.0-*" + }, + "frameworks": { + "net451": { }, + "netcoreapp1.0": { + "imports": [ + "dnxcore50", + "portable-net451+win8" + ], + "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0-*", + "type": "platform" + } + } + } + }, + "publishOptions": { + "include": [ + "wwwroot", + "web.config" + ] + }, + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": { + "version": "1.0.0-*", + "imports": "portable-net45+wp80+win8+wpa81+dnxcore50" + }, + "Microsoft.AspNetCore.Razor.Tools": { + "version": "1.0.0-*", + "imports": [ + "portable-net45+wp80+win8+wpa81+dnxcore50" + ] + } + }, + "scripts": { + "postpublish": "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" + } +} \ No newline at end of file diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/custom.css b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/custom.css new file mode 100644 index 000000000000..26d311c5ac30 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/custom.css @@ -0,0 +1,18 @@ + +.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; +} + + diff --git a/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/index.html b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/index.html new file mode 100644 index 000000000000..42ae8919b9d9 --- /dev/null +++ b/aspnet/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui/index.html @@ -0,0 +1,120 @@ + + + + + + ToDo API + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
+
+ + \ No newline at end of file diff --git a/common/authors.txt b/common/authors.txt index 8a0e43bbea41..459ed7c76aca 100644 --- a/common/authors.txt +++ b/common/authors.txt @@ -22,3 +22,4 @@ .. _Barry Dorrans: https://twitter.com/blowdart .. _Cesar Blum Silveira: https://github.com/cesarbs .. _Victor Hurdugaci: https://twitter.com/victorhurdugaci +.. _Shayne Boyer: https://twitter.com/spboyer