| | | 1 | | using ArturRios.Output; |
| | | 2 | | using Microsoft.AspNetCore.Mvc; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Configuration; |
| | | 6 | | |
| | | 7 | | /// <summary>Service registrations shared by web APIs built with this library.</summary> |
| | | 8 | | public static class ServiceCollectionExtensions |
| | | 9 | | { |
| | | 10 | | /// <param name="services">The service collection to register into.</param> |
| | | 11 | | extension(IServiceCollection services) |
| | | 12 | | { |
| | | 13 | | /// <summary>Replaces ASP.NET Core's default invalid-model-state response with a 400 result carrying a failed |
| | | 14 | | /// <see cref="DataOutput{T}"/> whose errors list each invalid parameter and its message, so validation failures |
| | | 15 | | /// have the same shape as every other failed response.</summary> |
| | | 16 | | /// <returns>The same <paramref name="services"/> instance, for chaining.</returns> |
| | | 17 | | public IServiceCollection AddInvalidModelStateEnvelope() => |
| | 19 | 18 | | services.Configure<ApiBehaviorOptions>(options => |
| | 19 | 19 | | { |
| | 18 | 20 | | options.InvalidModelStateResponseFactory = context => |
| | 18 | 21 | | { |
| | 1 | 22 | | var errors = context.ModelState |
| | 1 | 23 | | .Where(e => e.Value?.Errors.Count > 0) |
| | 2 | 24 | | .Select(e => $"Parameter: {e.Key} | Error: {e.Value?.Errors.First().ErrorMessage}").ToArray(); |
| | 18 | 25 | | |
| | 1 | 26 | | var output = DataOutput<string>.New |
| | 1 | 27 | | .WithData(string.Empty) |
| | 1 | 28 | | .WithErrors(errors); |
| | 18 | 29 | | |
| | 1 | 30 | | return new BadRequestObjectResult(output); |
| | 18 | 31 | | }; |
| | 37 | 32 | | }); |
| | | 33 | | } |
| | | 34 | | } |