Skip to content

Instantly share code, notes, and snippets.

@sampletext32
Created November 22, 2021 06:57
Show Gist options
  • Save sampletext32/14952f02bcc6471921dcb51400f0f13d to your computer and use it in GitHub Desktop.
Save sampletext32/14952f02bcc6471921dcb51400f0f13d to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Filters
{
public class ValidateModelFilter : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
string message = string.Join("\n",
context
.ModelState
.Select(e => e.Value.Errors)
.Where(e => e.Count > 0)
.SelectMany(e => e)
.Select(e => e.ErrorMessage)
);
context.Result = new BadRequestObjectResult(
message
);
return;
}
await next();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment