Skip to content

Commit 648477d

Browse files
committed
feat: Add filter to validate model state
1 parent 101ddef commit 648477d

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using Microsoft.AspNetCore.Mvc.Filters;
3+
4+
namespace ReferenceProject.Filters
5+
{
6+
public class ValidateModelFilter: IActionFilter
7+
{
8+
public void OnActionExecuted(ActionExecutedContext context)
9+
{
10+
11+
}
12+
13+
public void OnActionExecuting(ActionExecutingContext context)
14+
{
15+
if (!context.ModelState.IsValid)
16+
{
17+
context.Result = new BadRequestObjectResult(context.ModelState);
18+
}
19+
}
20+
}
21+
}

ProjectTemplates/AspNetCore.WebApi/ReferenceProject/ReferenceProject/Startup.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
using Microsoft.Extensions.Logging;
1414
using Newtonsoft.Json;
1515
using Newtonsoft.Json.Serialization;
16+
using ReferenceProject.Filters;
1617
using ReferenceProject.Middleware;
1718
using ReferenceProject.Modules;
1819

@@ -62,7 +63,10 @@ public void ConfigureServices(IServiceCollection services)
6263
.AddScoped<IUrlHelper>(x => x
6364
.GetRequiredService<IUrlHelperFactory>()
6465
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext))
65-
.AddMvc()
66+
.AddMvc(options =>
67+
{
68+
options.Filters.Add(new ValidateModelFilter());
69+
})
6670
.AddJsonOptions(options =>
6771
{
6872
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

0 commit comments

Comments
 (0)