如何在Azure Function中配置OpenApiRequestBody?

Siv*_*air 6 c# azure openapi

我想用 OpenApi 注释来装饰我的 azure c# 函数。该函数接受 JSON 模式作为参数。如何在注释中提及这一点。

想知道如何配置下面的注释

[OpenApiRequestBody(contentType: "json", bodyType: typeof(System.Text.Json.JsonDocument), Description = "Parameters",Example =typeof(Parameters))]

public class ModifyOrder
    {
        [FunctionName("ModifyOrder")]
        [OpenApiOperation(operationId: "run", tags: new[] { "Modify Order" })]
        [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
        [OpenApiRequestBody(contentType: "json", bodyType: typeof(System.Text.Json.JsonDocument), 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; }
    }
Run Code Online (Sandbox Code Playgroud)

小智 10

OpenApiRequestBody在您的示例中要关注的主要参数是bodyType。这里可以省略参数Example并以不同的方式配置(稍后解释)。不要使用JsonDocument而是使用您的Parameters类- 这将在 Swagger 定义中bodyType公开该类的特征。Parameters

您不能使用Parameters类本身来表示有效的示例,而应该创建一个继承的专用类,OpenApiExample<T>或者在您的情况下OpenApiExample<Parameters>,然后在该类中重写Build方法来构造Parameters. 然后,您可以通过使用属性装饰Parameters类来公开您的示例[OpenApiExample<T>](就像您所做的那样,但使​​用示例类类型!)。

有几件事值得注意OpenApiRequestBody,更一般地说,这个库 -Description的属性OpenApiRequestBody目前无法按预期工作;描述文本不会在 Swagger 定义中呈现requestBody。这引出了我的下一点,即(在撰写本文时)这个库 - Microsoft.Azure.WebJobs.Extensions.OpenApi - 处于预发布状态(0.7.2),因此似乎包含正如我自己发现的,有些错误。

我在ModifyOrder下面修改了你的课程;希望这个版本能够帮助解答您的问题!

public static class ModifyOrder
{
    [FunctionName("ModifyOrder")]
    [OpenApiOperation(operationId: "run", tags: new[] { "Modify Order" })]
    [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
    [OpenApiRequestBody(contentType: "application/json", bodyType: typeof(Parameters), Description = "Parameters", Required = true)]
    [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(ParametersExample))]
public class Parameters
{
    /// <summary>The id of the customer in the context. This is also called payer, sub_account_id.</summary>
    [OpenApiPropertyDescription("The id of the customer in the context. This is also called payer, sub_account_id.")]
    [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>
    [OpenApiPropertyDescription("The order number. Used to uniquely identify a group of order lines.")]
    [Newtonsoft.Json.JsonProperty("orderNumber", Required = Newtonsoft.Json.Required.Always)]
    [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)]
    public string OrderNumber { get; set; }
}

public class ParametersExample : OpenApiExample<Parameters>
{
    public override IOpenApiExample<Parameters> Build(NamingStrategy namingStrategy = null)
    {
        this.Examples.Add(
            OpenApiExampleResolver.Resolve(
                "ParametersExample",
                new Parameters()
                {
                    CustomerId = "CUST12345",
                    OrderNumber = "ORD001"
                },
                namingStrategy
            ));

        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)