master
bicijinlian 4 years ago
parent 5c54a2cdcc
commit c3929e516b

@ -35,7 +35,7 @@ namespace SwaggerStudy.Controllers
var apiResult = new ResultBase() var apiResult = new ResultBase()
{ {
Code = 0, Code = 0,
Message="获取所有学生", Message = "获取所有学生",
Data = _studentServer.GetAll(), Data = _studentServer.GetAll(),
}; };
@ -59,8 +59,16 @@ namespace SwaggerStudy.Controllers
/// <summary> /// <summary>
/// 按学号获取学生 /// 按学号获取学生
/// </summary> /// </summary>
[HttpGet] /// <example>
public IActionResult Get(int studentId) /// 示例
/// ```
/// sfdfsdafsadfsaf
/// ```
/// </example>
/// <remarks>我是Remark注释</remarks>
/// <param name="studentId" example="1">学生Id(变量在路由中时example才有用)</param>
[HttpGet("{studentId:int}")]
public IActionResult Get([FromRoute]int studentId)
{ {
var apiResult = new ResultBase() var apiResult = new ResultBase()
{ {

@ -29,7 +29,7 @@ Swashbuckle.AspNetCore
# 入门 # # 入门 #
1. 安装 Nuget包到您的ASP.NET Core应用程序中。 1. 安装 Nuget包到您的**ASP.NET Core**应用程序中。
``` ```
Nuget包管理器命令: Install-Package Swashbuckle.AspNetCore -Version 5.6.2 Nuget包管理器命令: Install-Package Swashbuckle.AspNetCore -Version 5.6.2
@ -234,9 +234,10 @@ These packages are provided by the open-source community.
## Swashbuckle.AspNetCore.Swagger ## ## Swashbuckle.AspNetCore.Swagger ##
### Change the Path for Swagger JSON Endpoints ### ### 更改Swagger JSON端点的路径 ###
By default, Swagger JSON will be exposed at the following route - "/swagger/{documentName}/swagger.json". If necessary, you can change this when enabling the Swagger middleware. Custom routes MUST include the `{documentName}` parameter. 默认情况下,Swagger JSON将在以下路径公开 -- "/swagger//swagger.json"。
如有必要,您可以在启用 Swagger 中间件时更改此路径;自定义路由必须包含参数`{documentName}`
```csharp ```csharp
app.UseSwagger(c => app.UseSwagger(c =>
@ -245,7 +246,7 @@ app.UseSwagger(c =>
}) })
``` ```
_NOTE: If you're using the SwaggerUI middleware, you'll also need to update its configuration to reflect the new endpoints:_ _注意:如果您使用 SwaggerUI 中间件,则还需要更新其配置以反映新的终结点_
```csharp ```csharp
app.UseSwaggerUI(c => app.UseSwaggerUI(c =>
@ -254,13 +255,14 @@ app.UseSwaggerUI(c =>
}) })
``` ```
### Modify Swagger with Request Context ### ### 使用请求上下文修改 Swagger ###
If you need to set some Swagger metadata based on the current request, you can configure a filter that's executed prior to serializing the document. 如果你需要根据当前请求设置某些Swagger元数据, 可以设置在序列化文档之前执行的筛选器.
```csharp ```csharp
app.UseSwagger(c => app.UseSwagger(c =>
{ {
//配置筛选器
c.PreSerializeFilters.Add((swagger, httpReq) => c.PreSerializeFilters.Add((swagger, httpReq) =>
{ {
swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } }; swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } };
@ -268,11 +270,11 @@ app.UseSwagger(c =>
}); });
``` ```
The `OpenApiDocument` and the current `HttpRequest` are both passed to the filter. This provides a lot of flexibility. For example, you can add an explicit API server based on the "Host" header (as shown), or you could inspect session information or an Authorization header and remove operations from the document based on user permissions. `OpenApiDocument` 和 当前的`HttpRequest` 都会传递给筛选器. 这提供了很大的灵活性,比如:您可以基于"Host"标头(如下所示)添加显式 API 服务器也可以检查Session信息或Authorization标头并基于用户权限从文档中删除操作。
### Serialize Swagger in the 2.0 format ### ### 以2.0格式序列化Swagger ###
By default, Swashbuckle will generate and expose Swagger JSON in version 3.0 of the specification, officially called the OpenAPI Specification. However, to support backwards compatibility, you can opt to continue exposing it in the 2.0 format with the following option: 默认情况下Swashbuckle 将在规范的 3.0 版本(正式称为 OpenAPI 规范)中生成和公开 Swagger JSON。但是为了支持向后兼容性您可以选择继续使用 2.0 格式使用以下选项公开它:
```csharp ```csharp
app.UseSwagger(c => app.UseSwagger(c =>
@ -283,20 +285,20 @@ app.UseSwagger(c =>
## Swashbuckle.AspNetCore.SwaggerGen ## ## Swashbuckle.AspNetCore.SwaggerGen ##
### Assign Explicit OperationIds ### ### 显式指定操作标识:OperationIds ###
In Swagger, operations MAY be assigned an `operationId`. This ID MUST be unique among all operations described in the API. Tools and libraries (e.g. client generators) MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. 在Swagger中, 可以分配 `operationId`。 此ID在所有的操作API中保持唯一. 工具和库(例如客户端生成器)可以使用 operationId 来唯一标识操作,因此,建议遵循常见的编程命名约定。
Auto-generating an ID that matches these requirements, while also providing a name that would be meaningful in client libraries is a non-trivial task and so, Swashbuckle omits the `operationId` by default. However, if neccessary, you can assign `operationIds` by decorating individual routes OR by providing a custom strategy. 自动生成一个与这些需求相匹配的ID同时提供一个在客户端库中有意义的名称是一项非常重要的任务因此swashbuck默认情况下会忽略operationId。但是如果需要可以通过装饰各个路由或提供自定义策略来分配operationid。
__Option 1) Decorate routes with a `Name` property__ __选项 1) 使用Name属性装饰路由__
```csharp ```csharp
[HttpGet("{id}", Name = "GetProductById")] [HttpGet("{id}", Name = "GetProductById")]
public IActionResult Get(int id) // operationId = "GetProductById" public IActionResult Get(int id) // operationId = "GetProductById"
``` ```
__Option 2) Provide a custom strategy__ __选项 2) 提供自定义策略__
```csharp ```csharp
// Startup.cs // Startup.cs
@ -304,7 +306,7 @@ services.AddSwaggerGen(c =>
{ {
... ...
// Use method name as operationId // 使用方法名作为 operationId
c.CustomOperationIds(apiDesc => c.CustomOperationIds(apiDesc =>
{ {
return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null; return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
@ -316,18 +318,18 @@ services.AddSwaggerGen(c =>
public IActionResult GetProductById(int id) // operationId = "GetProductById" public IActionResult GetProductById(int id) // operationId = "GetProductById"
``` ```
_NOTE: With either approach, API authors are responsible for ensuring the uniqueness of `operationIds` across all Operations_ _注意对于这两种方法API创建者负责确保所有操作的operationid是唯一的_
### List Operation Responses ### ### 列出操作响应 ###
By default, Swashbuckle will generate a "200" response for each operation. If the action returns a response DTO, then this will be used to generate a schema for the response body. For example ... 默认情况下Swashbuckle 将针对每个操作生成"200"响应。如果操作返回响应 DTO则此操作将用于为响应正文生成架构。例如
```csharp ```csharp
[HttpPost("{id}")] [HttpPost("{id}")]
public Product GetById(int id) public Product GetById(int id)
``` ```
Will produce the following response metadata: 将生成以下响应元数据:
``` ```
responses: { responses: {
@ -344,9 +346,9 @@ responses: {
} }
``` ```
#### Explicit Responses #### #### 显式响应 ####
If you need to specify a different status code and/or additional responses, or your actions return `IActionResult` instead of a response DTO, you can explicitly describe responses with the `ProducesResponseTypeAttribute` that ships with ASP.NET Core. For example ... 如果需要指定不同的状态代码和(或)其他响应,或者您的操作返回 IActionResult 而不是响应DTO则可以使用附带的ProducesResponseTypeAttribute显式描述ASP.NET Core 响应。例如
```csharp ```csharp
[HttpPost("{id}")] [HttpPost("{id}")]
@ -356,7 +358,7 @@ If you need to specify a different status code and/or additional responses, or y
public IActionResult GetById(int id) public IActionResult GetById(int id)
``` ```
Will produce the following response metadata: 将生成以下响应元数据:
``` ```
responses: { responses: {
@ -390,9 +392,9 @@ responses: {
} }
``` ```
### Flag Required Parameters and Schema Properties ### ### 标记所需的参数和架构属性 ###
In a Swagger document, you can flag parameters and schema properties that are required for a request. If a parameter (top-level or property-based) is decorated with the `BindRequiredAttribute` or `RequiredAttribute`, then Swashbuckle will automatically flag it as a "required" parameter in the generated Swagger: 在Swagger文档中可以标记请求所需的参数和架构属性。如果一个参数顶层或基于属性被BindRequiredAttribute或RequiredAttribute修饰那么Swashbuckle将在生成的Swagger中自动将其标记为“required”参数:
```csharp ```csharp
// ProductsController.cs // ProductsController.cs
@ -413,7 +415,7 @@ public class PagingParams
} }
``` ```
In addition to parameters, Swashbuckle will also honor the `RequiredAttribute` when used in a model that's bound to the request body. In this case, the decorated properties will be flagged as "required" properties in the body description: 除了参数之外当在绑定到请求主体的模型中使用时Swashbuckle还将遵循RequiredAttribute。在这种情况下修饰的属性将被标记为主体描述中的必需属性:
```csharp ```csharp
// ProductsController.cs // ProductsController.cs
@ -434,15 +436,33 @@ public class Product
} }
``` ```
### Include Descriptions from XML Comments ### ### 包括来自XML注释的说明 ###
To enhance the generated docs with human-friendly descriptions, you can annotate controller actions and models with [Xml Comments](http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx) and configure Swashbuckle to incorporate those comments into the outputted Swagger JSON: 为了用人性化的描述增强生成的文档,您可以用[Xml Comments](http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx)来注释控制器操作和模型并配置swashbuck以将这些注释合并到输出的Swagger JSON中:
1. Open the Properties dialog for your project, click the "Build" tab and ensure that "XML documentation file" is checked. This will produce a file containing all XML comments at build-time. 1. 打开项目的"属性"对话框,单击"生成"选项卡,并确保选中"XML 文档文件"。这将在生成时生成包含所有 XML 注释的文件。
_At this point, any classes or methods that are NOT annotated with XML comments will trigger a build warning. To suppress this, enter the warning code "1591" into the "Suppress warnings" field in the properties dialog._ _此时未使用“ML注释”注释的任何类或方法都将触发生成警告。若要禁止显示此状态请在属性对话框中的"Suppress warnings"字段中输入警告代码"1591"_
2. Configure Swashbuckle to incorporate the XML comments on file into the generated Swagger JSON: **特别说明**:上面项目属性对话框中的设置,会有些关于路径的小问题,可以直接编辑项目设置文件`xxxx.csproj` 如下(详见[微软官网配置](https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-5.0&tabs=visual-studio#add-and-configure-swagger-middleware)
``` xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<!--XML注释配置 开始-->
<GenerateDocumentationFile>true</GenerateDocumentationFile><!--生成xml注释文件-->
<NoWarn>$(NoWarn);1591</NoWarn><!--忽略1591警告-->
<!--XML注释配置 结束-->
</PropertyGroup>
//其它配置
</Project>
```
2. 配置 Swashbuckle 以将文件上的 XML 注释合并到生成的 Swagger JSON 中:
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -460,17 +480,48 @@ To enhance the generated docs with human-friendly descriptions, you can annotate
} }
``` ```
3. Annotate your actions with summary, remarks, param and response tags: 可以综合使用其它方法,比如
```
public void ConfigureServices(IServiceCollection services)
{
//其它代码
// 配置SwaggerGen
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo{Version = "v1",Title = "ToDo API"});
//设置Swagger JSON和UI的注释路径
//写法1
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
//写法2
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlFiles = Directory.GetFiles(basePath, "*.xml").ToList();
foreach (var item in xmlFiles)
{
//增加第二个参数True:包括控制器的注释不传或为false则只显示Action上的注释
c.IncludeXmlComments(item, true);
}
});
}
```
**特别注意**IncludeXmlComments(x)方法有重载IncludeXmlComments(x,y) 当第二个参数为true时刚包含控制器的注释否则只包括Action方法注释
3. 使用摘要、备注、参数和响应标记注释您的操作:
```csharp ```csharp
/// <summary> /// <summary>
/// Retrieves a specific product by unique id /// 按唯一id检索特定产品
/// </summary> /// </summary>
/// <remarks>Awesomeness!</remarks> /// <remarks>太棒了!</remarks>
/// <param name="id" example="123">The product id</param> /// <param name="id" example="123">产品Id</param>
/// <response code="200">Product created</response> /// <response code="200">产品已创建</response>
/// <response code="400">Product has missing/invalid values</response> /// <response code="400">产品缺少值或者值无效!</response>
/// <response code="500">Oops! Can't create your product right now</response> /// <response code="500">哎呀!现在无法创建产品!</response>
[HttpGet("{id}")] [HttpGet("{id}")]
[ProducesResponseType(typeof(Product), 200)] [ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)] [ProducesResponseType(typeof(IDictionary<string, string>), 400)]
@ -478,32 +529,33 @@ To enhance the generated docs with human-friendly descriptions, you can annotate
public Product GetById(int id) public Product GetById(int id)
``` ```
4. You can also annotate types with summary and example tags: 4. 还可以使用摘要和示例标记对类型进行注释:
```csharp ```csharp
//产品类
public class Product public class Product
{ {
/// <summary> /// <summary>
/// The name of the product /// 产品名称
/// </summary> /// </summary>
/// <example>Men's basketball shoes</example> /// <example>男子篮球鞋</example>
public string Name { get; set; } public string Name { get; set; }
/// <summary> /// <summary>
/// Quantity left in stock /// 剩余库存量
/// </summary> /// </summary>
/// <example>10</example> /// <example>10</example>
public int AvailableStock { get; set; } public int AvailableStock { get; set; }
} }
``` ```
5. Rebuild your project to update the XML Comments file and navigate to the Swagger JSON endpoint. Note how the descriptions are mapped onto corresponding Swagger fields. 5. 重新编译、构建项目以更新XML注释文件并导航到 Swagger JSON 终结点。请注意如何将描述映射到相应的 Swagger 字段。
_NOTE: You can also provide Swagger Schema descriptions by annotating your API models and their properties with summary tags. If you have multiple XML comments files (e.g. separate libraries for controllers and models), you can invoke the IncludeXmlComments method multiple times and they will all be merged into the outputted Swagger JSON._ _说明您还可以通过用摘要标记注释API模型及其属性来提供Swagger模式描述。如果您有多个XML注释文件例如用于控制器和模型的单独库则可以多次调用IncludeXmlComments方法它们将全部合并到输出的Swagger JSON中._
### Provide Global API Metadata ### ### 提供全局API元数据 ###
In addition to "PathItems", "Operations" and "Responses", which Swashbuckle generates for you, Swagger also supports global metadata (see https://swagger.io/specification/#oasObject). For example, you can provide a full description for your API, terms of service or even contact and licensing information: 除了Swashbuck为您生成的“PathItems”、“Operations”和“Responses”之外Swagger还支持全局元数据请参见https://swagger.io/specification/#oasObject). 例如您可以提供API的完整描述、服务条款甚至联系人和许可信息:
```csharp ```csharp
c.SwaggerDoc("v1", c.SwaggerDoc("v1",
@ -527,11 +579,12 @@ c.SwaggerDoc("v1",
); );
``` ```
_TIP: Use IntelliSense to see what other fields are available._ _提示: 使用智能感知查看哪些其他字段可用._
### Generate Multiple Swagger Documents ### ### 生成多Swagger文档 ###
With the setup described above, the generator will include all API operations in a single Swagger document. However, you can create multiple documents if necessary. For example, you may want a separate document for each version of your API. To do this, start by defining multiple Swagger docs in `Startup.cs`: 通过上述设置生成器将在一个单独的Swagger文档中包含所有API操作。但是如果需要可以创建多个文档。
例如您可能希望API的每个版本都有一个单独的文档。为此首先在`Startup.cs`中定义多个Swagger文档:
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -541,13 +594,13 @@ services.AddSwaggerGen(c =>
}) })
``` ```
_Take note of the first argument to SwaggerDoc. It MUST be a URI-friendly name that uniquely identifies the document. It's subsequently used to make up the path for requesting the corresponding Swagger JSON. For example, with the default routing, the above documents will be available at "/swagger/v1/swagger.json" and "/swagger/v2/swagger.json"._ _注意SwaggerDoc的第一个参数。它必须是唯一标识文档的URI友好名称。它随后被用来组成请求相应Swagger JSON的路径。例如使用默认路由时上述文档将位于"/swagger/v1/swagger.json"和"/swagger/v2/swagger.json"._
Next, you'll need to inform Swashbuckle which actions to include in each document. Although this can be customized (see below), by default, the generator will use the `ApiDescription.GroupName` property, part of the built-in metadata layer that ships with ASP.NET Core, to make this distinction. You can set this by decorating individual actions OR by applying an application wide convention. 下一步您需要通知swashbuck要在每个文档中包含哪些操作。尽管可以自定义见下文但默认情况下生成器将使用`ApiDescription.GroupName`属性它是随附的ASP.NET Core内置元数据层的一部分来区分这一点。您可以通过装饰单个操作或应用应用程序范围的约定来设置此设置。
#### Decorate Individual Actions #### #### 装饰 Actions ####
To include an action in a specific Swagger document, decorate it with the `ApiExplorerSettingsAttribute` and set `GroupName` to the corresponding document name (case sensitive): 若要在特定的Swagger文档中包含操作请使用“ApiExplorerSettingsAttribute”对其进行修饰并将“GroupName”设置为相应的文档名称区分大小写
```csharp ```csharp
[HttpPost] [HttpPost]
@ -555,9 +608,10 @@ To include an action in a specific Swagger document, decorate it with the `ApiEx
public void Post([FromBody]Product product) public void Post([FromBody]Product product)
``` ```
#### Assign Actions to Documents by Convention #### #### 按公约为文档分组 ####
To group by convention instead of decorating every action, you can apply a custom controller or action convention. For example, you could wire up the following convention to assign actions to documents based on the controller namespace. 要按约定分组而不是装饰每个Action方法可以应用自定义控制器或操作约定类。
例如,您可以将以下约定连接起来,根据控制器名称空间将操作分配给文档。
```csharp ```csharp
// ApiExplorerGroupPerVersionConvention.cs // ApiExplorerGroupPerVersionConvention.cs
@ -583,9 +637,9 @@ public void ConfigureServices(IServiceCollection services)
} }
``` ```
#### Customize the Action Selection Process #### #### 自定义Action选择过程 ####
When selecting actions for a given Swagger document, the generator invokes a `DocInclusionPredicate` against every `ApiDescription` that's surfaced by the framework. The default implementation inspects `ApiDescription.GroupName` and returns true if the value is either null OR equal to the requested document name. However, you can also provide a custom inclusion predicate. For example, if you're using an attribute-based approach to implement API versioning (e.g. Microsoft.AspNetCore.Mvc.Versioning), you could configure a custom predicate that leverages the versioning attributes instead: 在为给定的Swagger文档选择操作时生成器将针对框架显示的每个“ApiDescription”调用一个“DocInclusionPredicate”。默认实现检查`ApiDescription.GroupName`如果值为null或等于请求的文档名则返回true。但是您也可以提供一个自定义的包含谓词。例如如果您使用基于属性的方法来实现API版本控制例如。Microsoft.AspNetCore.Mvc.Versioning则可以配置一个利用版本控制属性的自定义谓词
```csharp ```csharp
c.DocInclusionPredicate((docName, apiDesc) => c.DocInclusionPredicate((docName, apiDesc) =>
@ -601,13 +655,13 @@ c.DocInclusionPredicate((docName, apiDesc) =>
}); });
``` ```
#### Exposing Multiple Documents through the UI #### #### 通过UI公开多个文档 ####
If you're using the `SwaggerUI` middleware, you'll need to specify any additional Swagger endpoints you want to expose. See [List Multiple Swagger Documents](#list-multiple-swagger-documents) for more. 如果使用的是“SwaggerUI”中间件则需要指定要公开的任何其他Swagger端点。有关详细信息请参见[列出多个Swagger文档](#list-multiple-swagger-documents)。
### Omit Obsolete Operations and/or Schema Properties ### ### 忽略过时的操作和(或)架构属性 ###
The [Swagger spec](http://swagger.io/specification/) includes a `deprecated` flag for indicating that an operation is deprecated and should be refrained from use. The Swagger generator will automatically set this flag if the corresponding action is decorated with the `ObsoleteAttribute`. However, instead of setting a flag, you can configure the generator to ignore obsolete actions altogether: [Swagger spec](http://swagger.io/specification/) 包含一个“deprecated”标志用于指示某个操作已弃用应避免使用。如果相应的操作用“ObsoleteAttribute”修饰则Swagger生成器将自动设置此标志。但是您可以将生成器配置为完全忽略过时的操作而不是设置标志
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -617,7 +671,7 @@ services.AddSwaggerGen(c =>
}; };
``` ```
A similar approach can also be used to omit obsolete properties from Schemas in the Swagger output. That is, you can decorate model properties with the `ObsoleteAttribute` and configure Swashbuckle to omit those properties when generating JSON Schemas: 在Swagger输出中也可以使用类似的方法从`Model`中省略过时的属性。也就是说,您可以用`ObsoleteAttribute`修饰模型属性并配置swashbuck以在生成JSON模式时忽略这些属性:
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -627,13 +681,13 @@ services.AddSwaggerGen(c =>
}; };
``` ```
### Omit Arbitrary Operations ### ### 忽略任意操作 ###
You can omit operations from the Swagger output by decorating individual actions OR by applying an application wide convention. 您可以通过装饰单个操作或应用应用程序范围 `convention`来从 Swagger 输出中忽略操作。
#### Decorate Individual Actions #### #### 单独装饰 Action ####
To omit a specific action, decorate it with the `ApiExplorerSettingsAttribute` and set the `IgnoreApi` flag: 若要忽略某个特定的接口(控制器方法),请使用`ApiExplorerSettingsAttribute` 对其进行修饰,并设置`IgnoreApi`标志:
```csharp ```csharp
[HttpGet("{id}")] [HttpGet("{id}")]
@ -641,9 +695,9 @@ To omit a specific action, decorate it with the `ApiExplorerSettingsAttribute` a
public Product GetById(int id) public Product GetById(int id)
``` ```
#### Omit Actions by Convention #### #### 按约定器`Convention`忽略Action ####
To omit actions by convention instead of decorating them individually, you can apply a custom action convention. For example, you could wire up the following convention to only document GET operations: 要按约定省略操作而不是单独装饰它们可以应用自定义操作约定。例如可以将以下约定连接到仅document GET操作
```csharp ```csharp
// ApiExplorerGetsOnlyConvention.cs // ApiExplorerGetsOnlyConvention.cs
@ -666,11 +720,11 @@ public void ConfigureServices(IServiceCollection services)
} }
``` ```
### Customize Operation Tags (e.g. for UI Grouping) ### ### 自定义操作标签(如自定义用户界面) ###
The [Swagger spec](http://swagger.io/specification/) allows one or more "tags" to be assigned to an operation. The Swagger generator will assign the controller name as the default tag. This is important to note if you're using the `SwaggerUI` middleware as it uses this value to group operations. [Swagger 规范](http://swagger.io/specification/) 允许将一个或多个`tags`分配给操作。Swagger生成器将指定控制器名称作为默认标记。如果使用的是`SwaggerUI`中间件,这一点很重要,因为它使用这个值来分组操作。
You can override the default tag by providing a function that applies tags by convention. For example, the following configuration will tag, and therefore group operations in the UI, by HTTP method: 您可以通过提供按约定应用标记的函数来重写默认标记。例如以下配置将通过HTTP方法标记UI中的操作从而对操作进行分组
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -680,9 +734,9 @@ services.AddSwaggerGen(c =>
}; };
``` ```
### Change Operation Sort Order (e.g. for UI Sorting) ### ### 更改操作排序顺序(例如 UI 排序) ###
By default, actions are ordered by assigned tag (see above) before they're grouped into the path-centric, nested structure of the [Swagger spec](http://swagger.io/specification). But, you can change the default ordering of actions with a custom sorting strategy: 默认情况下,动作在被分组到[Swagger 规范](http://swagger.io/specification)的以路径为中心的嵌套结构之前按指定的标记(见上文)排序. 但是,您可以使用自定义排序策略更改操作的默认顺序
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -692,11 +746,11 @@ services.AddSwaggerGen(c =>
}; };
``` ```
_NOTE: This dictates the sort order BEFORE actions are grouped and transformed into the Swagger format. So, it affects the ordering of groups (i.e. Swagger "PathItems"), AND the ordering of operations within a group, in the Swagger output._ _注意: 这规定了在将操作分组并转换为Swagger格式之前的排序顺序。因此它会影响组的顺序Swagger“PathItems”以及组内操作的顺序在Swagger输出中。_
### Customize Schema Id's ### ### 自定义 Schema Id's ###
If the generator encounters complex parameter or response types, it will generate a corresponding JSON Schema, add it to the global `components/schemas` dictionary, and reference it from the operation description by unique Id. For example, if you have an action that returns a `Product` type, then the generated schema will be referenced as follows: 如果生成器遇到复杂的参数或响应类型它将生成相应的JSON架构并将其添加到全局“组件/架构”字典中并通过唯一Id从操作描述中引用它。例如如果您有一个返回`Product`类型的操作,则生成的架构将被引用如下:
``` ```
responses: { responses: {
@ -713,7 +767,7 @@ responses: {
} }
``` ```
However, if it encounters multiple types with the same name but different namespaces (e.g. `RequestModels.Product` & `ResponseModels.Product`), then Swashbuckle will raise an exception due to "Conflicting schemaIds". In this case, you'll need to provide a custom Id strategy that further qualifies the name: 但是,如果它遇到多个名称空间(例如`RequestModels.Product` & `ResponseModels.Product`)那么swashbuck将由于“冲突的schemaIds”而引发异常。在这种情况下您需要提供一个定制的Id策略来进一步限定名称
```csharp ```csharp
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
@ -723,11 +777,12 @@ services.AddSwaggerGen(c =>
}; };
``` ```
### Override Schema for Specific Types ### ### 覆盖特定类型的架构 ###
Out-of-the-box, Swashbuckle does a decent job at generating JSON Schemas that accurately describe your request and response payloads. However, if you're customizing serialization behavior for certain types in your API, you may need to help it out. 开箱即用Swashbulk在生成准确描述请求和响应负载的JSON模式方面做得很好。但是如果要为API中的某些类型自定义序列化行为则可能需要帮助。
For example, you might have a class with multiple properties that you want to represent in JSON as a comma-separated string. To do this you would probably implement a custom `JsonConverter`. In this case, Swashbuckle doesn't know how the converter is implemented and so you would need to provide it with a Schema that accurately describes the type: 例如您可能有一个具有多个属性的类您希望在JSON中将这些属性表示为逗号分隔的字符串。为此您可能需要实现一个自定义的`JsonConverter`。在这种情况下Swashbuck不知道转换器是如何实现的因此您需要为它提供一个能够准确描述类型的模式
例如您可能有一个具有多个属性的类您希望在JSON中将这些属性表示为逗号分隔的字符串。为此您可能需要实现一个自定义的`JsonConverter`。在这种情况下Swashbuck不知道转换器是如何实现的因此您需要为它提供一个能够准确描述类型的模式
```csharp ```csharp
// PhoneNumber.cs // PhoneNumber.cs
@ -748,15 +803,15 @@ services.AddSwaggerGen(c =>
}; };
``` ```
### Extend Generator with Operation, Schema & Document Filters ### ### 使用Operation、Schema和Document筛选器扩展生成器 ###
Swashbuckle exposes a filter pipeline that hooks into the generation process. Once generated, individual metadata objects are passed into the pipeline where they can be modified further. You can wire up custom filters to enrich the generated "Operations", "Schemas" and "Documents". Swashbuckle 公开一个筛选器管道,该管道连接到生成过程。生成后,单个元数据对象将传递到管道中,并可进一步修改它们。您可以连接自定义筛选器以丰富生成的`Operations` `Schemas``Documents`.
#### Operation Filters #### #### Operation 筛选器 ####
Swashbuckle retrieves an `ApiDescription`, part of ASP.NET Core, for every action and uses it to generate a corresponding `OpenApiOperation`. Once generated, it passes the `OpenApiOperation` and the `ApiDescription` through the list of configured Operation Filters. Swashbuckle为每个`Operation`检索一个 `ApiDescription`ASP.NET Core的一部分并使用它生成相应的`OpenApiOperation`,一旦生成,它会将`OpenApiOperation`和`ApiDescription`传递给配置的操作筛选器列表。
In a typical filter implementation, you would inspect the `ApiDescription` for relevant information (e.g. route info, action attributes etc.) and then update the `OpenApiOperation` accordingly. For example, the following filter lists an additional "401" response for all actions that are decorated with the `AuthorizeAttribute`: 在一个典型的过滤器实现中,您需要检查`ApiDescription`中的相关信息(例如路由信息、操作属性等),然后相应地更新`OpenApiOperation`。例如,下面的过滤器列出了用`AuthorizeAttribute`修饰的所有操作的附加"401"响应:
```csharp ```csharp
// AuthResponsesOperationFilter.cs // AuthResponsesOperationFilter.cs
@ -783,7 +838,7 @@ services.AddSwaggerGen(c =>
_NOTE: Filter pipelines are DI-aware. That is, you can create filters with constructor parameters and if the parameter types are registered with the DI framework, they'll be automatically injected when the filters are instantiated_ _NOTE: Filter pipelines are DI-aware. That is, you can create filters with constructor parameters and if the parameter types are registered with the DI framework, they'll be automatically injected when the filters are instantiated_
#### Schema Filters #### #### Schema 筛选器 ####
Swashbuckle generates a Swagger-flavored [JSONSchema](http://swagger.io/specification/#schemaObject) for every parameter, response and property type that's exposed by your controller actions. Once generated, it passes the schema and type through the list of configured Schema Filters. Swashbuckle generates a Swagger-flavored [JSONSchema](http://swagger.io/specification/#schemaObject) for every parameter, response and property type that's exposed by your controller actions. Once generated, it passes the schema and type through the list of configured Schema Filters.
@ -818,7 +873,7 @@ services.AddSwaggerGen(c =>
}; };
``` ```
#### Document Filters #### #### Document 筛选器 ####
Once an `OpenApiDocument` has been generated, it too can be passed through a set of pre-configured Document Filters. This gives full control to modify the document however you see fit. To ensure you're still returning valid Swagger JSON, you should have a read through the [specification](http://swagger.io/specification/) before using this filter type. Once an `OpenApiDocument` has been generated, it too can be passed through a set of pre-configured Document Filters. This gives full control to modify the document however you see fit. To ensure you're still returning valid Swagger JSON, you should have a read through the [specification](http://swagger.io/specification/) before using this filter type.

@ -71,6 +71,7 @@ namespace SwaggerStudy
//此对象可以使用规范扩展进行扩展 //此对象可以使用规范扩展进行扩展
Extensions = new Dictionary<string, IOpenApiExtension>() Extensions = new Dictionary<string, IOpenApiExtension>()
{ {
} }
}); });
@ -81,6 +82,16 @@ namespace SwaggerStudy
setup.IncludeXmlComments(xmlFile, true); setup.IncludeXmlComments(xmlFile, true);
} }
setup.TagActionsBy(des =>
{
List<string> i = new List<string>()
{
des.ActionDescriptor.RouteValues["controller"].ToString()
};
return i;
});
}); });
//配置SwaggerGen //配置SwaggerGen
@ -123,7 +134,7 @@ namespace SwaggerStudy
app.UseSwaggerUI(setup => app.UseSwaggerUI(setup =>
{ {
//swagger 访问页面前缀默认swagger //swagger 访问页面前缀默认swagger
//SwaggerUi首页地址baseUrl+前辍+index.html 默认:http://localhost:8080/swagger/index.html //SwaggerUi首页地址baseUrl+前辍+index.html 默认:/swagger/index.html
setup.RoutePrefix = "Swagger"; setup.RoutePrefix = "Swagger";
setup.SwaggerEndpoint("/WebApi/swagger/DemoName/swagger.json", "WebApi 测试版"); setup.SwaggerEndpoint("/WebApi/swagger/DemoName/swagger.json", "WebApi 测试版");
}); });

Loading…
Cancel
Save