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中关于Swagger的一些配置-LMLPHP

ABP中关于Swagger的一些配置-LMLPHP

隐藏 Abp 相关的 endpoints

services.AddAbpSwaggerGen(
    options =>
    {
        options.HideAbpEndpoints();
    }
);

隐藏 Abp 相关的 schemas

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中关于Swagger的一些配置-LMLPHP

  • 通过 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();
});

接口注释

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));
<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

修改 Schema 默认的时间格式

ABP中关于Swagger的一些配置-LMLPHP

options.MapType<DateTime>(() => new OpenApiSchema { Type = "string", Example = new Microsoft.OpenApi.Any.OpenApiString("2000-01-01 00:00:00") });

结束

10-17 15:52