Skip to content

Instantly share code, notes, and snippets.

@caisback
Last active March 14, 2023 07:48
Show Gist options
  • Save caisback/3be7bcf3116a2be1f5f6fa9cc2f7c37e to your computer and use it in GitHub Desktop.
Save caisback/3be7bcf3116a2be1f5f6fa9cc2f7c37e to your computer and use it in GitHub Desktop.
Azure Function .Net6 in-proc with OpenAPI - default function
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 TheApp.Functions.UserAdministration.User
{
    public class GetUsersFunction
    {
        private readonly ILogger<GetUsersFunction> _logger;

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

        [FunctionName("GetUsersFunction")]
        [OpenApiOperation(operationId: "Run", tags: new[] { "Users" })]
        [OpenApiSecurity("function_keyX", SecuritySchemeType.ApiKey, Name = "codeX", In = OpenApiSecurityLocationType.Query)]
        [OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
        [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "users")] 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);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment