-->
Developer Community for Visual Studio Product family. Get help from our community supported forum.
By Shayne Boyer and Scott Addie
View or download sample code (how to download)
There are three main components to Swashbuckle:
Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose
SwaggerDocument
objects as JSON endpoints.Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds
SwaggerDocument
objects directly from your routes, controllers, and models. It's typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.
Package installation
Swashbuckle can be added with the following approaches:
From the Package Manager Console window:
Go to View > Other Windows > Package Manager Console
Navigate to the directory in which the TodoApi.csproj file exists
Execute the following command:
From the Manage NuGet Packages dialog:
- Right-click the project in Solution Explorer > Manage NuGet Packages
- Set the Package source to 'nuget.org'
- Ensure the 'Include prerelease' option is enabled
- Enter 'Swashbuckle.AspNetCore' in the search box
- Select the latest 'Swashbuckle.AspNetCore' package from the Browse tab and click Install
- Right-click the Packages folder in Solution Pad > Add Packages...
- Set the Add Packages window's Source drop-down to 'nuget.org'
- Ensure the 'Show pre-release packages' option is enabled
- Enter 'Swashbuckle.AspNetCore' in the search box
- Select the latest 'Swashbuckle.AspNetCore' package from the results pane and click Add Package
Run the following command from the Integrated Terminal:
Run the following command:
Add and configure Swagger middleware
In the Startup
class, import the following namespace to use the OpenApiInfo
class:
Add the Swagger generator to the services collection in the Startup.ConfigureServices
method:
In the Startup.Configure
method, enable the middleware for serving the generated JSON document and the Swagger UI:
The preceding UseSwaggerUI
method call enables the Static File Middleware. If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project.
Launch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json
. The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).
The Swagger UI can be found at http://localhost:<port>/swagger
. Explore the API via Swagger UI and incorporate it in other programs.
Tip
To serve the Swagger UI at the app's root (http://localhost:<port>/
), set the RoutePrefix
property to an empty string:
If using directories with IIS or a reverse proxy, set the Swagger endpoint to a relative path using the ./
prefix. For example, ./swagger/v1/swagger.json
. Using /swagger/v1/swagger.json
instructs the app to look for the JSON file at the true root of the URL (plus the route prefix, if used). For example, use http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json
instead of http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json
.
Customize and extend
Swagger provides options for documenting the object model and customizing the UI to match your theme.
In the Startup
class, add the following namespaces:
API info and description
The configuration action passed to the AddSwaggerGen
method adds information such as the author, license, and description:
The Swagger UI displays the version's information:
XML comments
XML comments can be enabled with the following approaches:
- Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
- Manually add the highlighted lines to the .csproj file:
- Right-click the project in Solution Explorer and select Properties.
- Check the XML documentation file box under the Output section of the Build tab.
- From the Solution Pad, press control and click the project name. Navigate to Tools > Edit File.
- Manually add the highlighted lines to the .csproj file:
- Open the Project Options dialog > Build > Compiler
- Check the Generate xml documentation box under the General Options section
Manually add the highlighted lines to the .csproj file:
Manually add the highlighted lines to the .csproj file:
Enabling XML comments provides debug information for undocumented public types and members. Undocumented types and members are indicated by the warning message. For example, the following message indicates a violation of warning code 1591:
To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the project file. Appending the warning codes to $(NoWarn);
applies the C# default values too.
To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor directives. This approach is useful for code that shouldn't be exposed via the API docs. In the following example, warning code CS1591 is ignored for the entire Program
class. Enforcement of the warning code is restored at the close of the class definition. Specify multiple warning codes with a comma-delimited list.
Configure Swagger to use the XML file that's generated with the preceding instructions. For Linux or non-Windows operating systems, file names and paths can be case-sensitive. For example, a TodoApi.XML file is valid on Windows but not CentOS.
In the preceding code, Reflection is used to build an XML file name matching that of the web API project. The AppContext.BaseDirectory property is used to construct a path to the XML file. Some Swagger features (for example, schemata of input parameters or HTTP methods and response codes from the respective attributes) work without the use of an XML documentation file. For most features, namely method summaries and the descriptions of parameters and response codes, the use of an XML file is mandatory.
Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the section header. Add a <summary> element above the Delete
action:
The Swagger UI displays the inner text of the preceding code's <summary>
element:
The UI is driven by the generated JSON schema:
Add a <remarks> element to the Create
action method documentation. It supplements information specified in the <summary>
element and provides a more robust Swagger UI. The <remarks>
element content can consist of text, JSON, or XML.
Notice the UI enhancements with these additional comments:
Data annotations
Decorate the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.
Add the [Required]
attribute to the Name
property of the TodoItem
class:
The presence of this attribute changes the UI behavior and alters the underlying JSON schema:
Add the [Produces('application/json')]
attribute to the API controller. Its purpose is to declare that the controller's actions support a response content type of application/json:
The Response Content Type drop-down selects this content type as the default for the controller's GET actions:
As the usage of data annotations in the web API increases, the UI and API help pages become more descriptive and useful.
Describe response types
Developers consuming a web API are most concerned with what's returned—specifically response types and error codes (if not standard). The response types and error codes are denoted in the XML comments and data annotations.
The Create
action returns an HTTP 201 status code on success. An HTTP 400 status code is returned when the posted request body is null. Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. Fix that problem by adding the highlighted lines in the following example:
The Swagger UI now clearly documents the expected HTTP response codes:
In ASP.NET Core 2.2 or later, conventions can be used as an alternative to explicitly decorating individual actions with [ProducesResponseType]
. For more information, see Use web API conventions.
Customize the UI
The stock UI is both functional and presentable. However, API documentation pages should represent your brand or theme. Branding the Swashbuckle components requires adding the resources to serve static files and building the folder structure to host those files.
If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project:
The preceding NuGet package is already installed if targeting .NET Core 2.x and using the metapackage.
Enable Static File Middleware:
Acquire the contents of the dist folder from the Swagger UI GitHub repository. This folder contains the necessary assets for the Swagger UI page.
Create a wwwroot/swagger/ui folder, and copy into it the contents of the dist folder.
Create a custom.css file, in wwwroot/swagger/ui, with the following CSS to customize the page header:
Reference custom.css in the index.html file inside ui folder, after any other CSS files:
Browse to the index.html page at http://localhost:<port>/swagger/ui/index.html
. Enter https://localhost:<port>/swagger/v1/swagger.json
in the header's textbox, and click the Explore button. The resulting page looks as follows:
There's much more you can do with the page. See the full capabilities for the UI resources at the Swagger UI GitHub repository.
How can I make CTRL + / toggle a comment in Visual Studio, as it does with XCode and Eclipse?
heavyd7 Answers
Toggle single line comment and toggle block comment commands have been added in VS 2019 for C#
You can change the shortcut for these commands to whatever you want in Tools -> Options -> Environment -> Keyboard, search for Edit.ToggleBlockComment or Edit.ToggleLineComment.
Amc Turn Tv Series
You can't make it toggle without going into either a macro or other VS extension.
However, I always setup VS to comment with Ctrl + / and uncomment to Ctrl + Shift + /
You can customize the keyboard shortcuts by going int the 'Tools' menu and selecting 'Options'. Then select 'Keyboard' from the 'Environment' branch. From there you can bind the Edit.CommentSelection
and Edit.UncommentSelection
commands to whichever keyboard shortcuts you'd like.
Here is a plugin to have the almighty 'Toggle Comment' command...
1- Download and Install >https://marketplace.visualstudio.com/items?itemName=munyabe.ToggleComment
2- Restart VS
3- Go to 'Tools > Options... > Environment > Keyboard'
4- Search for the command 'ToggleComment' & Bind it to your favorite key
5- Enjoy
(Thank you, I had gave up but finally found this easy way to do it ;D)
If you have ReSharper installed (and using VS without it is/was tedious), you can assign a single key to the command ReSharper.ReSharper_LineComment
.
Visual Studio For Mac Turn Off Xml Comment Code
For instance, I bind the keyboard shortcut Ctrl-K, Ctrl-C
to the command, and then if I use it on a line that is uncommented, it comments it, and if the line is commented, it will uncomment it.
Ctrl-K and Ctrl-C will comment one or more selected lines.
Ctrl-K and Ctrl-U will uncomment one or more selected lines.
You can get toolbar icons that will do this by adding the 'Text Editor' toolbar. In the toolbar area right-click and select 'Text Editor' This will add a strip of icon buttons like this:
You can customize this strip by selecting the dropdown at the end of the ribbon:
To edit the keyboard combination go to Tools-Options and select Keyboard under the Environment tree. Here you can change the keys used to trigger the Comment and Uncomment actions:
Brad PattonBrad PattonI don't know if it is the same in 2012 but in 2015 you can.
Go to Tools > Options > Environment > Keyboard
Either, find 'VisualD.ToggleCommentSelection' or
Search for 'comment' and the bottom option should be 'VisualD.ToggleCommentSelection'
If you're using Resharper, there is an almost identical alternative:
Right Alt+/
By using this single shortcut, you can simply toggle between commenting/uncommenting code.
phuclv