Create a Custom OpenApiResponseWithBody Attribute which holds multiple attribute of the same type

86 views Asked by At
[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))]

These are the ones we want to add in that particular attribute which is used by all the Functions in a Function App For eg:

 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;
     }
 }

and use that instead of all that messy code.

I followed this particual approach and it didnt work for the mentioned use case

1

There are 1 answers

1
Pavan On

Create a Custom OpenApiResponseWithBody Attribute which holds multiple attribute of the same type

I have created Http trigger function with dotnet runtime stack in vs code.

I have created custom attributes and added in the function code by using below code:

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

The above function holds multiple attributes but when it ran given response like below:

enter image description here

enter image description here