Created
November 22, 2021 06:57
-
-
Save sampletext32/14952f02bcc6471921dcb51400f0f13d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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