Azure 函数、Swagger、OpenApi

问题描述 投票:0回答:2

正如我正在使用的标题:Azure Function、Swagger 和 OpenApi。

看下面的代码:

[Function("v1/job/selectAll/{agentId}")]
[OpenApiOperation(operationId: "selectAllJpbs", tags: new[] { nameof(TctJob) }, Summary = "Select all jobs.", Description = "This select all the jobs of an agent.", Visibility = OpenApiVisibilityType.Important)]
//[OpenApiSecurity("petstore_auth", SecuritySchemeType.OAuth2, Flows = typeof(PetStoreAuth))]
[OpenApiParameter(name: "agentId", In = ParameterLocation.Query, Description = "The id of the agent to download the jobs", Required = true, Type = typeof(Guid))]
//[OpenApiRequestBody(contentType: "application/json", bodyType: typeof(List<TctJob>), Required = true, Description = "List of all the jobs of the requested agent.")]
//[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(System.Collections.Generic.List<ITctJob>), Summary = "Job list.", Description = "List of all the jobs.")]
[OpenApiResponseWithoutBody(statusCode: HttpStatusCode.BadRequest, Summary = "Invalid ID supplied", Description = "Invalid ID supplied")]
[OpenApiResponseWithoutBody(statusCode: HttpStatusCode.NotFound, Summary = "", Description = "")]
[OpenApiResponseWithoutBody(statusCode: HttpStatusCode.MethodNotAllowed, Summary = "Validation exception", Description = "Validation exception")]
public async Task<IActionResult> SelectAllJobs(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req,
    [FromRoute(Name = "agentId")] Guid agentId)
{ ... }

如果我运行此代码并尝试访问 Swagger 主页 (

.../api/swagger/ui
),一切正常。

现在,如果我从

OpenApiRequestBody
OpenApiResponseWithBody
行中删除注释,则会收到以下错误:

获取错误。内部服务器错误 http://localhost:7031/api/swagger.json

请注意,swagger.json 文件正是它应该在的位置...

有关环境的一些信息:

  • 目标框架:.Net 6
  • Azure 函数版本:4
  • AzureExtensions.Swashbuckle:3.3.2

更新

这是我的

.csproj
文件:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <OutputType>Exe</OutputType>
        <!--<Nullable>enable</Nullable>-->
        <AssemblyVersion>1.0.0</AssemblyVersion>
        <PackageVersion>1.0.0</PackageVersion>
        <Authors>The Cloud Team</Authors>
        <Company>The Cloud Team</Company>
        <Description>This package contains the Database Updater service.</Description>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.16.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Abstractions" Version="1.2.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.11.0" />
    </ItemGroup>
    <ItemGroup>
      <ProjectReference Include="..\..\..\TCT.Backend.Services.Common\TCT.Backend.Services.Common\TCT.Backend.Services.Common\TCT.Backend.Services.Common.csproj" />
      <ProjectReference Include="..\..\..\TCT.Common\TCT.Common\TCT.Common.csproj" />
    </ItemGroup>
    <ItemGroup>
        <None Update="host.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
            <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
    </ItemGroup>
</Project>

怎么了?有什么建议或解决方法吗?

问候, 阿蒂里奥

c# azure-functions swagger openapi
2个回答
0
投票

我创建了一个 Azure 函数

.NET 6 Isolated

感谢@Justin Yoo提供代码。

我尝试使用

OpenApiRequestBody
OpenApiResponseWithBody
来运行该函数 我能够运行代码,没有任何错误。

我的

.csproj
文件。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.14.1" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.5.1" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.10.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
  </ItemGroup>
</Project>

我的样品

Function1.cs

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;

  [Function("v1/job/selectAll/{agentId}")]
  [OpenApiOperation(operationId: "selectAllJpbs", tags: new[] { "TctJob" }, Summary = "Select all jobs.", Description = "This select all the jobs of an agent.", Visibility = OpenApiVisibilityType.Important)]
  //[OpenApiSecurity("petstore_auth", SecuritySchemeType.OAuth2, Flows = typeof(PetStoreAuth))]
  [OpenApiParameter(name: "agentId", In = ParameterLocation.Query, Description = "The id of the agent to download the jobs", Required = true, Type = typeof(Guid))]
  [OpenApiRequestBody(contentType: "application/json", bodyType: typeof(string), Required = true, Description = "List of all the jobs of the requested agent.")]
  [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string), Summary = "Job list.", Description = "List of all the jobs.")]
  [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.BadRequest, Summary = "Invalid ID supplied", Description = "Invalid ID supplied")]
  [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.NotFound, Summary = "", Description = "")]
  [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.MethodNotAllowed, Summary = "Validation exception", Description = "Validation exception")]


  public HttpResponseData GetAll([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
  {
      _logger.LogInformation("C# HTTP trigger function processed a request.");

      var response = req.CreateResponse(HttpStatusCode.OK);
      response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

      response.WriteString("Welcome to Azure Functions!");

      return response;
  }

我的

Program.cs
文件:

using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Extensions;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())
    .Build();

host.Run();

输出:

enter image description here

Swagger.json enter image description here


0
投票

进一步检查后,我注意到这条线

[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(List<ITctJob>), Summary = "Job list.", Description = "List of all the jobs of the agent.")]

contentType: "application/json"
bodyType: typeof(List<ITctJob>)
。所以我决定将 bodyType 从
typeof(List<ITctJob>)
更改为
typeof(string)
并且它有效!

所以正确的代码是:

[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string), Summary = "Job list.", Description = "List of all the jobs of the agent.")]

谁能解释一下为什么?

© www.soinside.com 2019 - 2024. All rights reserved.