有没有办法从预编译的 C# Azure Functions 中自动生成 Swagger 标签?

Is there a way to automatically generate Swagger tags from precomipled C# Azure Functions?(有没有办法从预编译的 C# Azure Functions 中自动生成 Swagger 标签?)
本文介绍了有没有办法从预编译的 C# Azure Functions 中自动生成 Swagger 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人知道任何可用于注释预编译 C# Azure 函数的 .NET 属性,以便它可以自动生成 Swagger 标记?例如,我想在 Swagger 中自动生成标签"条目:

Is anyone aware of any .NET attributes that can be used to annotate a precompiled C# Azure Function so it can generate Swagger tags automatically? For example, I would like to auto-generate the "tags" entry in Swagger:

/api/v1/revision:
    get:
      operationId: /api/v1/revision/get
      tags:
        - System
      produces: []
      consumes: []
      parameters: []
      description: Gets the API version
      responses:
        '200':
          description: Success operation
      security:
        - apikeyQuery: []

这是我的 C# 函数:

Here is my C# function:

 public static class VersioningService
    {
        [FunctionName("ApiVersion")]
        public static async Task<HttpResponseMessage> ApiVersion([HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/revision")]HttpRequestMessage req, TraceWriter log)
        {
            return req.CreateResponse(HttpStatusCode.OK, "<p>API Version: 1.0340");
        }
    }

推荐答案

找到这篇文章:

  • 以编程方式为函数创建 Swagger 定义

我已经使用 powershell 实现了这些步骤.
该脚本假定您有一个已配置的 host.json 文件:

I've impletemented the steps using powershell.
The script assumes that you have a configured host.json file:

{
  "swagger": {
    "enabled": true
  }
}

此脚本仅适用于 Azure Function 运行时 v1,尚未为运行时 v2 实现 swagger 生成

This script only work for Azure Function runtime v1, swagger generation is not yet implemented for runtime v2

function Get-KuduApiAuthorisationHeaderValueAzure {
    Param
    (
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$functionappName
    )
    Begin {               
        $resourceType = "Microsoft.Web/sites/config"
        $resourceName = "$functionappName/publishingcredentials"
        $publishingCredentials = Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType $resourceType -ResourceName $resourceName -Action list -ApiVersion 2015-08-01 -Force

        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword)))
        return $base64AuthInfo
    }
}

function Get-MasterAPIKey {
    Param
    (
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$functionappName
    )
    Begin {               
        $kuduApiAuthorisationToken = Get-KuduApiAuthorisationHeaderValueAzure -resourceGroupName $resourceGroupName -functionappName $functionappName
        $apiUrl = "https://$functionappName.scm.azurewebsites.net/api/functions/admin/masterkey"
        $response = Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization = ("Basic {0}" -f $kuduApiAuthorisationToken);"If-Match"="*"}
        return $response.masterKey
    }
}

function Get-FunctionsApiJwt {
    Param
    (
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$functionappName
    )
    Begin {               
        $base64AuthInfo = Get-KuduApiAuthorisationHeaderValueAzure -resourceGroupName $resourceGroupName -functionappName $functionappName
        $apiUrl = "https://$functionappName.scm.azurewebsites.net/api/functions/admin/token"
        $jwt = Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method GET

        return $jwt
    }
}

function Generate-SwaggerDefinition {
    Param
    (
        [Parameter(Mandatory = $true)]
        [string]$resourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$functionappName
    )
    Begin {   

        # Get the swagger documentation key
        $masterKey = Get-MasterAPIKey -resourceGroupName $resourceGroupName -functionappName $functionappName
        $apiUrl = "https://$functionappName.azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey"
        $swaggerdocumentationkey = (Invoke-RestMethod -Uri $apiUrl -Headers @{"x-functions-key"=$masterKey} -Method Post).value

        # Update the resource
        $config = Get-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType "microsoft.web/sites/config" -Name "$functionappName/web" -ApiVersion "2015-08-01"
        $config.Properties.apiDefinition = @{"url"="https://$functionappName.azurewebsites.net/admin/host/swagger?code=$swaggerdocumentationkey"}
        $config | Set-AzureRmResource -Force -ApiVersion "2015-08-01"

        # Generate the swagger definition
        $jwt = Get-FunctionsApiJwt -resourceGroupName $resourceGroupName -functionappName $functionappName
        $swaggerDefinition = (Invoke-RestMethod -Uri "https://$functionappName.azurewebsites.net/admin/host/swagger/default?code=$swaggerdocumentationkey" -Headers @{Authorization=("Bearer {0}" -f $jwt)} -Method Get)

        # Save the swagger definition
        Invoke-RestMethod -Uri "https://$functionappName.azurewebsites.net/admin/host/swagger?code=$swaggerdocumentationkey" -ContentType 'application/json' -Headers @{Authorization=("Bearer {0}" -f $jwt)} -Method Post -Body (ConvertTo-Json $swaggerDefinition -Depth 100)
    }
}

你可以这样调用这个脚本:

you can call this script like that:

Generate-SwaggerDefinition -resourceGroupName "myresourcegroupname" -functionappName "myfunctionappname"

编辑

新创建的函数应用默认使用 TLS 1.2,因此您需要在 Powershell 脚本顶部添加此行:

Newly created function apps use TLS 1.2 by default so you need to add this line at the top of the Powershell script:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

这篇关于有没有办法从预编译的 C# Azure Functions 中自动生成 Swagger 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)