-
Notifications
You must be signed in to change notification settings - Fork 1
/
RequireBodyFilter.cs
41 lines (37 loc) · 1.35 KB
/
RequireBodyFilter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace OptionalBody
{
public class RequireBodyFilter : ActionFilterAttribute
{
public RequireBodyFilter()
{
// Run before the ModelStateInvalidFilter
Order = -2001;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var controllerActionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
var methodParameters = controllerActionDescriptor.MethodInfo.GetParameters();
for (var i = 0; i < context.ActionDescriptor.Parameters.Count; i++)
{
var parameter = context.ActionDescriptor.Parameters[i];
if (parameter.BindingInfo?.BindingSource != BindingSource.Body)
{
continue;
}
if (methodParameters[i].HasDefaultValue)
{
continue;
}
var boundValue = context.ActionArguments[parameter.Name];
if (boundValue == null)
{
context.ModelState.AddModelError(parameter.Name, "Request body is required.");
break;
}
}
}
}
}