|
| 1 | +using System.ComponentModel.DataAnnotations; |
| 2 | +using System.Net; |
| 3 | +using FluentValidation; |
| 4 | +using Microsoft.AspNetCore.Mvc; |
| 5 | +using Microsoft.Azure.Functions.Worker; |
| 6 | +using Microsoft.Azure.Functions.Worker.Http; |
| 7 | +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; |
| 8 | +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using Microsoft.OpenApi.Models; |
| 11 | + |
| 12 | +namespace SampleFunctionApp |
| 13 | +{ |
| 14 | + public class SampleFunction |
| 15 | + { |
| 16 | + private readonly ILogger _logger; |
| 17 | + private readonly IValidator<SampleInput> _validator; |
| 18 | + |
| 19 | + public SampleFunction(ILoggerFactory loggerFactory, IValidator<SampleInput> validator) |
| 20 | + { |
| 21 | + _logger = loggerFactory.CreateLogger<SampleFunction>(); |
| 22 | + _validator = validator; |
| 23 | + } |
| 24 | + |
| 25 | + [Function("SampleFunction")] |
| 26 | + [OpenApiOperation(operationId: "sampleFunction", tags: new[] { "sample" }, Summary = "Sample input validation", Visibility = OpenApiVisibilityType.Important)] |
| 27 | + [OpenApiRequestBody(contentType: "application/json", bodyType: typeof(SampleInput), Required = true)] |
| 28 | + [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.OK)] |
| 29 | + [OpenApiResponseWithBody(statusCode: HttpStatusCode.BadRequest, contentType: "application/json", bodyType: typeof(ProblemDetails), Summary = "Invalid input supplied")] |
| 30 | + public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req) |
| 31 | + { |
| 32 | + _logger.LogInformation("C# HTTP trigger function processed a request."); |
| 33 | + |
| 34 | + var input = await req.ReadFromJsonAsync<SampleInput>(); |
| 35 | + if (input is null) |
| 36 | + { |
| 37 | + var error = req.CreateResponse(HttpStatusCode.BadRequest); |
| 38 | + await error.WriteAsJsonAsync( |
| 39 | + new ProblemDetails |
| 40 | + { |
| 41 | + Status = (int)HttpStatusCode.BadRequest, |
| 42 | + Title = "Missing body" |
| 43 | + }); |
| 44 | + |
| 45 | + return error; |
| 46 | + } |
| 47 | + |
| 48 | + var validationResult = await _validator.ValidateAsync(input); |
| 49 | + if (!validationResult.IsValid) |
| 50 | + { |
| 51 | + var error = req.CreateResponse(HttpStatusCode.BadRequest); |
| 52 | + await error.WriteAsJsonAsync( |
| 53 | + new ProblemDetails |
| 54 | + { |
| 55 | + Status = (int)HttpStatusCode.BadRequest, |
| 56 | + Title = "One or more validation errors occurred.", |
| 57 | + Extensions = { |
| 58 | + ["errors"] = validationResult.Errors.Select(e => new |
| 59 | + { |
| 60 | + e.ErrorCode, |
| 61 | + e.PropertyName, |
| 62 | + e.ErrorMessage |
| 63 | + }) |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + return error; |
| 68 | + } |
| 69 | + |
| 70 | + return req.CreateResponse(HttpStatusCode.OK); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments