首页 > 解决方案 > Azure Functions 和 Swagger UI - 如何在 Swagger UI 中显示查询字符串参数?

问题描述

我有以下由 HTTP 触发的 Azure 函数。我已经使用此处的链接为我的端点设置了 Swagger 。以下 API 需要一组查询字符串参数,即“姓名”、“电子邮件”、“电话”,因此它可以对目标对象进行一些搜索。目前,该功能的主体当然没有实现,但这对于这个问题并不重要。

我的问题:如何在 swagger UI 中显示查询字符串参数?

功能:

[FunctionName(nameof(GetBookingCalendarsFunction))]
 public async Task<IActionResult> GetAllAsync(
        [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "bookings")] HttpRequest request,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        return new OkObjectResult($"Name: {request.Query["name"]}, email: {request.Query["email"]}, phone: {request.Query["phone"]}");
    }

此功能的招摇 UI

在此处输入图像描述

注意:我不想使用路由值而不是查询字符串参数,因为这些参数是可选的,并且调用者可能不想提供其中之一。

例如,我尝试了以下操作,但如果您删除任何参数,它将失败并显示 404,因为它将它们作为路由的一部分(即使它会在 Swagger 中显示它们)

  [FunctionName(nameof(GetBookingCalendarsFunction))]
    public async Task<IActionResult> GetAllAsync(
        [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "bookings/name={name}&email={email}&phone={phone}")] HttpRequest request,
        string name, string email, string phone,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        return new OkObjectResult($"Name: {request.Query["name"]}, email: {request.Query["email"]}, phone: {request.Query["phone"]}");
    }

我已经在谷歌上搜索了几个小时,但到目前为止找不到任何有用的东西。感谢你的帮助。

标签: swaggerazure-functionsswagger-uiazure-http-trigger

解决方案


由于您使用包将 Swagger 集成到 Azure 功能中,因此我们可以根据您的需要AzureExtensions.Swashbuckle使用 Attribute来配置查询字符串。QueryStringParameter更多详情,请参考这里

例如

 [FunctionName("GetBookingCalendarsFunction")]
        [QueryStringParameter("name", "this is name", DataType = typeof(string), Required = false)]
        [QueryStringParameter("email", "this is email", DataType = typeof(string), Required = false)]
        [QueryStringParameter("phone", "this is phone", DataType = typeof(string), Required = false)]
        public static async Task<IActionResult> GetAllAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "bookings")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

           

            return new OkObjectResult($"Name: {req.Query["name"]}, email: {req.Query["email"]}, phone: {req.Query["phone"]}");
        }

在此处输入图像描述


推荐阅读