创建一个自定义 OpenApiResponseWithBody 属性,其中包含相同类型的多个属性

问题描述 投票:0回答:1
[OpenApiResponseWithBody(HttpStatusCode.OK, "application/json", typeof(SampleResponseDto))]
[OpenApiResponseWithBody(HttpStatusCode.InternalServerError, "application/json", typeof(SampleErrorResponseDto))]
[OpenApiResponseWithBody(HttpStatusCode.Unauthorized, "application/json", typeof(ErrorResponseDto))]
[OpenApiResponseWithBody(HttpStatusCode.Forbidden, "application/json", typeof(ErrorResponseDto))]

这些是我们要添加到特定属性中的属性,该属性由函数应用程序中的所有函数使用,例如:

 public class OpenApiDefaultsAttribute : Attribute, IMetadatAttribute
 {

     public Attribute[] Process()
     {
         var attributes = new Attribute[] {
             new OpenApiResponseWithBodyAttribute(HttpStatusCode.Unauthorized, "application/json", typeof(ErrorResponseDto)),
             new OpenApiResponseWithBodyAttribute(HttpStatusCode.Forbidden, "application/json", typeof(ErrorResponseDto))
         };
         return attributes;
     }
 }

并使用它来代替那些混乱的代码。

我遵循了这个特定方法,但它不适用于上述用例

.net azure-functions openapi custom-attributes azure-functions-isolated
1个回答
0
投票

创建一个自定义 OpenApiResponseWithBody 属性,其中包含相同类型的多个属性

我在 vs code 中使用 dotnet 运行时堆栈创建了 Http 触发函数。

我创建了自定义属性并使用以下代码添加到功能代码中:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.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;
using Newtonsoft.Json;

namespace Company.Function
{
    public class HttpTriggerWithOpenAPICSharp1
    {
        private readonly ILogger<HttpTriggerWithOpenAPICSharp1> _logger;

        public HttpTriggerWithOpenAPICSharp1(ILogger<HttpTriggerWithOpenAPICSharp1> log)
        {
            _logger = log;
        }

        [FunctionName("HttpTriggerWithOpenAPICSharp1")]
        [OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
        [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
        [OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
        [OpenApiDefaults]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }

    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public class OpenApiDefaultsAttribute : Attribute, IMetadatAttribute
    {
        public Attribute[] Process()
        {
            var attributes = new Attribute[]
            {
                new OpenApiResponseWithBodyAttribute(HttpStatusCode.OK, "application/json", typeof(SampleResponseDto)),
                new OpenApiResponseWithBodyAttribute(HttpStatusCode.InternalServerError, "application/json", typeof(SampleErrorResponseDto)),
                new OpenApiResponseWithBodyAttribute(HttpStatusCode.Unauthorized, "application/json", typeof(ErrorResponseDto)),
                new OpenApiResponseWithBodyAttribute(HttpStatusCode.Forbidden, "application/json", typeof(ErrorResponseDto))
            };
            return attributes;
        }
    }

    internal interface IMetadatAttribute
    {
    }

    // Define your response DTOs
    public class SampleResponseDto
    {
        // Properties for response type 1
    }

    public class SampleErrorResponseDto
    {
        // Properties for response type 2
    }

    public class ErrorResponseDto
    {
        // Properties for response type 3
    }
}

enter image description here

上面的函数拥有多个属性,但是当它运行时给出如下响应:

enter image description here

enter image description here

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