ABP中關于Swagger的一些配置
Abp 集成 Swagger 官方文檔, 請參考 Swagger Integration
AspNetCore 配置 Swagger, 請參考 Swashbuckle.AspNetCore
本文的項目環境是 AspNetCore 6.0 + Volo.Abp.Swashbuckle 6.0.2
Abp 中默認的基礎配置如下:
public override void ConfigureServices(ServiceConfigurationContext context)
{
var services = context.Services;
services.AddAbpSwaggerGen(
options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
}
);
}
這樣的配置,很難滿足我們的需求,比如它默認顯示了 Abp 相關的 endpoints 和 schema, 沒有詳細的接口注釋等


隱藏 Abp 相關的 endpoints
Abp 官方文檔 提及了這個操作,代碼如下
services.AddAbpSwaggerGen(
options =>
{
options.HideAbpEndpoints();
}
);
隱藏 Abp 相關的 schemas
這個在官網中沒有發現,搜索到可以實現自定義的 ISchemaFilter
參考: Hide Endpoints And Schemas from Swagger / OpenAPI
public class HideAbpSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
context.SchemaRepository.Schemas.RemoveAll(item => item.Key.StartsWith("Volo."));
}
}
//使用方法
services.AddAbpSwaggerGen(
options =>
{
options.SchemaFilter<HideAbpSchemaFilter>();
}
);
隱藏 Abp 默認生成的響應類型
Abp 默認生成了 400,401,403,404,500,501 相關的響應

通過
AbpAspNetCoreMvcModule這個模塊的源碼,我們看到了它的默認實現如下:
Configure<AbpRemoteServiceApiDescriptionProviderOptions>(options =>
{
var statusCodes = new List<int>
{
(int) HttpStatusCode.Forbidden,
(int) HttpStatusCode.Unauthorized,
(int) HttpStatusCode.BadRequest,
(int) HttpStatusCode.NotFound,
(int) HttpStatusCode.NotImplemented,
(int) HttpStatusCode.InternalServerError
};
options.SupportedResponseTypes.AddIfNotContains(statusCodes.Select(statusCode => new ApiResponseType
{
Type = typeof(RemoteServiceErrorResponse),
StatusCode = statusCode
}));
});
那就很好解決了,我們只要把它給清除就行了,代碼如下
Configure<AbpRemoteServiceApiDescriptionProviderOptions>(options =>
{
options.SupportedResponseTypes.Clear();
});
接口注釋
這個簡單,只要包含項目的 XML 文檔注釋就行
var xmlFilename1 = "EOA.User.WebApi.xml";
var xmlFilename2 = "EOA.User.Application.xml";
var xmlFilename3 = "EOA.User.Application.Contracts.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename1));
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename2));
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename3));
別忘了開啟生成項目的文檔注釋(可以直接編輯.csproj 文件)
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
修改 Schema 默認的時間格式

直接全局修改 DateTime 類型的 Schema 配置即可,給個默認的 Example
options.MapType<DateTime>(() => new OpenApiSchema { Type = "string", Example = new Microsoft.OpenApi.Any.OpenApiString("2000-01-01 00:00:00") });
結束
本文也是實際記錄我發現的一點小問題, 這么一頓操作下來是不是清爽多了

浙公網安備 33010602011771號