Skip to content

Instantly share code, notes, and snippets.

@ntakouris
Created July 30, 2019 08:47
Show Gist options
  • Save ntakouris/2654d6aa614c820a9d0b6cdd8d9ef3b2 to your computer and use it in GitHub Desktop.
Save ntakouris/2654d6aa614c820a9d0b6cdd8d9ef3b2 to your computer and use it in GitHub Desktop.
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
var errorsInModelState = context.ModelState
.Where(x => x.Value.Errors.Count > 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(x => x.ErrorMessage)).ToArray();
var errorResponse = new ErrorResponse();
foreach (var error in errorsInModelState)
{
foreach (var subError in error.Value)
{
var errorModel = new ErrorModel
{
FieldName = error.Key,
Message = subError
};
errorResponse.Errors.Add(errorModel);
}
}
context.Result = new BadRequestObjectResult(errorResponse);
return;
}
await next();
// after controller
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment