Azure Function OpenAPI规范同状态码多内容类型报错问题
解决Azure Function中OpenAPI重复状态码响应报错问题
问题场景
在Azure Function接口中,尝试为HttpStatusCode.OK(200状态码)同时配置application/json和application/xml两种响应类型的OpenApiResponseWithBody特性,期望生成包含两种内容类型的200响应OpenAPI文档,但运行时抛出如下错误:
An item with the same key has already been added. Key: 200 at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) at Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.DocumentHelper.GetOpenApiResponses(MethodInfo element, NamingStrategy namingStrategy, VisitorCollection collection, OpenApiVersionType version) at Microsoft.Azure.WebJobs.Extensions.OpenApi.Document.Build(Assembly assembly, OpenApiVersionType version) at Microsoft.Azure.WebJobs.Extensions.OpenApi.OpenApiTriggerFunctions.RenderSwaggerDocument(OpenApiHttpTriggerContext openApiContext, HttpRequest req, String extension, ExecutionContext ctx, ILogger log)
期望生成的OpenAPI YAML结构:
responses: '200': description: A Whatever content: application/json: schema: ... application/xml: schema: ...
报错原因
Azure Functions OpenAPI扩展在处理OpenApiResponseWithBody特性时,会将状态码作为字典的唯一键,每个状态码只能关联一个OpenApiResponseWithBody实例。添加两个相同状态码的该特性,会触发字典重复键冲突,导致报错。
解决方案
不要使用多个OpenApiResponseWithBody特性,改用OpenApiResponse特性,通过其Content属性传入多个OpenApiContent实例,每个实例对应一种媒体类型和响应Schema。
正确代码示例
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; using Microsoft.AspNetCore.Http; // 假设的JSON响应模型 public class JsonResponseModel { public string Message { get; set; } } // 假设的XML响应模型 public class XmlResponseModel { public string Message { get; set; } } public static class MyFunction { [FunctionName("GetData")] [OpenApiOperation(operationId: "GetData", tags: new[] { "data" })] [OpenApiResponse( statusCode: HttpStatusCode.OK, Description = "A Whatever", Content = new[] { new OpenApiContent( MediaType = "application/json", Schema = typeof(JsonResponseModel) ), new OpenApiContent( MediaType = "application/xml", Schema = typeof(XmlResponseModel) ) } )] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { // 根据请求头返回对应格式的响应 var acceptHeader = req.Headers["Accept"].ToString(); if (acceptHeader.Contains("application/xml")) { return new OkObjectResult(new XmlResponseModel { Message = "XML response content" }); } return new OkObjectResult(new JsonResponseModel { Message = "JSON response content" }); } }
效果验证
使用上述写法后,OpenAPI扩展会正确生成包含两种内容类型的200响应结构,与预期的YAML格式一致,同时不会再抛出重复键错误。
内容的提问来源于stack exchange,提问作者Ranvir
相关产品推荐
相关产品推荐

