Azure Function、Swagger、OpenApi

ccgok5k5  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(97)

就像我正在玩的标题一样: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),一切正常。
现在,如果我从OpenApiRequestBodyOpenApiResponseWithBody行中删除注解,我会得到以下错误:
获取错误。内部服务器错误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>


怎么了?有什么建议或变通办法吗?
问候你,阿蒂利奥

ryoqjall

ryoqjall1#

创建Azure Function .NET 6 Isolated
谢谢@Justin Yoo的代码。
我已经尝试通过使用OpenApiRequestBodyOpenApiResponseWithBody运行函数我能够运行代码没有任何错误。
我的.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();

  • 输出:*

x1c 0d1x的数据

  • Swagger.json*
cs7cruho

cs7cruho2#

经过进一步的检查,我注意到这条线

[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(List<ITctJob>),并且它可以工作!
所以正确的代码是:

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


有人能解释一下为什么吗?

相关问题