You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Azure Functions OpenAPI扩展时Swagger UI因大响应卡顿的解决办法

解决Swagger UI因大响应卡顿的方案

当接口返回2MB左右的大响应时,Swagger UI卡顿的核心原因是浏览器需要渲染大量JSON数据,导致DOM操作过载。以下是几种可行的解决办法:

1. 修正OpenAPI响应配置并简化示例渲染

你的代码中[OpenApiResponseWithBody]的contentType设置为text/plain,这会让Swagger UI以纯文本形式渲染完整响应内容,加重浏览器负担。建议改为application/json,并配置简化的响应示例,避免自动渲染全量数据:

[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", 
    bodyType: typeof(List<BookableResourcesResponse>), 
    Summary = "The response", 
    Description = "This returns the list of bookable resources",
    Example = typeof(BookableResourcesResponseExample))] // 使用简化的单条示例

同时自定义示例类,只返回单条数据的示例,而非全量列表:

public class BookableResourcesResponseExample : OpenApiExample<List<BookableResourcesResponse>>
{
    public override IOpenApiExample<List<BookableResourcesResponse>> Build(NamingStrategy namingStrategy = null)
    {
        this.Examples.Add(OpenApiExampleResolver.Resolve("Sample", new List<BookableResourcesResponse>
        {
            new BookableResourcesResponse { Id = "1", Name = "Sample Resource" } // 仅单条示例数据
        }, namingStrategy));
        return this;
    }
}

2. 开启响应压缩

在Azure Function App中启用动态压缩,减少传输到Swagger UI的响应体积:

  • 在Azure门户的Function App配置页面,进入Configuration > Application settings,添加设置:
    WEBSITE_USE_DYNAMIC_COMPRESSION = true
    
  • 若使用隔离模式的Function App,可在Program.cs中添加响应压缩中间件:
    builder.Services.AddResponseCompression(options =>
    {
        options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
            new[] { "application/json", "text/plain" });
    });
    builder.UseResponseCompression();
    

3. 接口改为分页返回

将批量返回数据改为分页模式,从根源上减小响应体积:

  • 修改函数参数,添加分页参数:
    public IActionResult GetBookableResources([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req, 
        [FromBody] BookableResourcesRequestBody reqBody,
        int page = 1, int pageSize = 50) // 新增分页参数
    {
        try
        {   
            var bookableResources = _bookableResourceService.GetBookableResources(reqBody, page, pageSize);
            var totalCount = _bookableResourceService.GetBookableResourcesCount(reqBody);
            return new OkObjectResult(new { Data = bookableResources, TotalCount = totalCount, Page = page, PageSize = pageSize });
        }
        catch (Exception ex)
        {
            _logger.LogError($"Get Bookable resources error: {ex.Message}");
            return new BadRequestObjectResult(ex.Message);
        }
    }
    
  • 同步更新OpenAPI响应类型为分页结果类:
    [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", 
        bodyType: typeof(PagedResult<BookableResourcesResponse>), 
        Summary = "The paginated response", 
        Description = "Returns paginated list of bookable resources")]
    
    分页结果类定义:
    public class PagedResult<T>
    {
        public List<T> Data { get; set; }
        public int TotalCount { get; set; }
        public int Page { get; set; }
        public int PageSize { get; set; }
    }
    

4. 自定义Swagger UI配置,禁用自动展开

通过修改OpenAPI配置,让Swagger UI默认不展开大响应内容,需用户手动点击查看:

  • 在Program.cs的OpenApi配置中添加自定义UI设置:
    services.AddSingleton<IOpenApiConfigurationOptions>(_ =>
    {
        var options = new OpenApiConfigurationOptions()
        {
            Info = new OpenApiInfo()
            {
                Version = "1.0.0",
                Title = "API",
                Description = "This is API."
            },
            Servers = DefaultOpenApiConfigurationOptions.GetHostNames(),
            OpenApiVersion = OpenApiVersionType.V3,
            IncludeRequestingHostName = true,
            ForceHttps = false,
            ForceHttp = false,
            // 自定义Swagger UI行为
            SwaggerUiConfig = new Dictionary<string, string>
            {
                { "defaultModelsExpandDepth", "-1" }, // 默认不展开模型列表
                { "defaultModelExpandDepth", "-1" }, // 默认不展开单个模型详情
                { "defaultModelRendering", "model" } // 使用模型视图而非示例视图
            }
        };
    
        return options;
    });
    

内容的提问来源于stack exchange,提问作者Loc Dai Le

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:08:21