@ -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.
_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:
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.
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.
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 ...
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 ...
@ -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:
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:
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:
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._
@ -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.
_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._
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:
_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`:
_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"._
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.
To include an action in a specific Swagger document, decorate it with the `ApiExplorerSettingsAttribute` and set `GroupName` to the corresponding document name (case sensitive):
@ -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:
#### 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.
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:
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:
@ -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:
@ -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.
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:
### 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:
_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._
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:
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:
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.
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:
### 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 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.
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`:
_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.