Skip to content

Commit

Permalink
Small clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
davidfowl committed Nov 23, 2024
1 parent 617dfee commit fb0032e
Showing 1 changed file with 4 additions and 11 deletions.
15 changes: 4 additions & 11 deletions Todo.Api/Filters/ValidationFilter.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System.Reflection;
using Microsoft.AspNetCore.Http.Metadata;
using MiniValidation;

namespace TodoApi;

public static class ValidationFilterExtensions
{
private static readonly ProducesResponseTypeMetadata ValidationErrorResponseMetadata =
new(400, typeof(HttpValidationProblemDetails), ["application/problem+json"]);

public static TBuilder WithParameterValidation<TBuilder>(this TBuilder builder, params Type[] typesToValidate) where TBuilder : IEndpointConventionBuilder
{
builder.Add(eb =>
Expand Down Expand Up @@ -35,7 +37,7 @@ public static TBuilder WithParameterValidation<TBuilder>(this TBuilder builder,
}

// We can respond with problem details if there's a validation error
eb.Metadata.Add(new ProducesResponseTypeMetadata(typeof(HttpValidationProblemDetails), 400, "application/problem+json"));
eb.Metadata.Add(ValidationErrorResponseMetadata);

eb.FilterFactories.Add((context, next) =>
{
Expand All @@ -56,13 +58,4 @@ public static TBuilder WithParameterValidation<TBuilder>(this TBuilder builder,

return builder;
}

// Equivalent to the .Produces call to add metadata to endpoints
private sealed class ProducesResponseTypeMetadata(Type type, int statusCode, string contentType) :
IProducesResponseTypeMetadata
{
public Type Type { get; } = type;
public int StatusCode { get; } = statusCode;
public IEnumerable<string> ContentTypes { get; } = [contentType];
}
}

0 comments on commit fb0032e

Please sign in to comment.