Skip to content

Instantly share code, notes, and snippets.

@maximgorbatyuk
Last active March 4, 2021 09:55
Show Gist options
  • Select an option

  • Save maximgorbatyuk/033a54c3f1d2ece0d4e90174b498bdb1 to your computer and use it in GitHub Desktop.

Select an option

Save maximgorbatyuk/033a54c3f1d2ece0d4e90174b498bdb1 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Utils.Serialization;
namespace YourNamespace
{
public class ValidationProblemDetailsResult : IActionResult
{
public async Task ExecuteResultAsync(ActionContext context)
{
var modelStateEntries = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.ToArray();
var errors = new List<ValidationError>();
if (modelStateEntries.Any())
{
foreach (var (key, value) in modelStateEntries)
{
errors.AddRange(value.Errors
.Select(modelStateError => new ValidationError(
name: key.ToSnakeCase(),
description: modelStateError.ErrorMessage)));
}
}
await new JsonErrorResponse<ValidationProblemDetails>(
context: context.HttpContext,
error: new ValidationProblemDetails(errors),
statusCode: ValidationProblemDetails.ValidationStatusCode).WriteAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment