如何在Azure Function C#函数中配置OpenApiRequestBody注解
C# Azure函数OpenApi参数规则声明方案
你当前的配置只需要调整OpenApiRequestBody注解的bodyType参数即可实现需求:你现在将bodyType指定为typeof(System.Text.Json.JsonDocument),会导致OpenApi生成器无法关联到你自定义Parameters类的字段约束,直接将该参数替换为typeof(Parameters)即可:
// 修正后的注解 [OpenApiRequestBody(contentType: "json", bodyType: typeof(Parameters), Description = "Parameters", Example = typeof(Parameters))]
修改完成后,OpenApi生成器会自动读取Parameters类的配置生成对应的JSON Schema规则:
- 字段标注的
[Required]特性会被识别为必填项 JsonProperty配置的序列化属性名、必填规则会同步到Schema- 字段的XML注释会作为每个属性的说明自动填充
完整修正代码示例
public class ModifyOrder { [FunctionName("ModifyOrder")] [OpenApiOperation(operationId: "run", tags: new[] { "Modify Order" })] [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)] // 仅修改此处的bodyType参数即可 [OpenApiRequestBody(contentType: "json", bodyType: typeof(Parameters), Description = "Parameters", Example = typeof(Parameters))] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")] public static async Task<IActionResult> run( [HttpTrigger(AuthorizationLevel.Function, "put", Route = null )] HttpRequest req, ILogger log) { log.LogInformation($"C# HTTP trigger function processed a request."); string ordernumber; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); ordernumber = data?.orderno; string responseMessage = $"Order:{ordernumber}"; return new OkObjectResult(responseMessage); } } [OpenApiExample(typeof(Parameters))] public class Parameters { /// <summary>The id of the customer in the context. This is also called payer, sub_account_id.</summary> [Newtonsoft.Json.JsonProperty("customerId", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string CustomerId { get; set; } /// <summary>The order number. Used to uniquely identify a group of order lines.</summary> [Newtonsoft.Json.JsonProperty("orderNumber", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string OrderNumber { get; set; } }
补充说明
- 如果你业务逻辑中确实需要用
JsonDocument或者动态类型接收原始请求,不需要修改函数的入参处理逻辑,仅修改注解中的bodyType即可:注解仅影响OpenApi文档的生成,不会干预实际运行时的请求处理 - 如果需要自定义请求示例的具体值,可以新增示例类实现
IOpenApiExample<Parameters>接口,返回你需要的示例内容,再把注解中的Example参数指定为该示例类的类型即可
内容的提问来源于stack exchange,提问作者Sivakumar G Nair
相关产品推荐
相关产品推荐

