Last active
February 1, 2019 02:55
-
-
Save enif-lee/6f315724e1782c61830666657751c3b8 to your computer and use it in GitHub Desktop.
ASP.NET MVC Empty Body Filter
This file contains hidden or 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
namespace Application.Infrastructures.Filters | |
{ | |
public class ValidateModelAttribute : ActionFilterAttribute | |
{ | |
private readonly ConcurrentDictionary<string, IList<string>> _bodyParameters = new ConcurrentDictionary<string, IList<string>>(); | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
base.OnActionExecuting(actionContext); | |
var request = actionContext.Request; | |
var arguments = actionContext.ActionArguments; | |
var bodyParameter = _bodyParameters.GetOrAdd( | |
((ReflectedHttpActionDescriptor) actionContext.ActionDescriptor).MethodInfo.ToString(), // this is full name for method (example: Namespace.ReturnType Namespace.Controller.ActionMethod(Namespace.SomeDto parameterName)) | |
_ => actionContext.ActionDescriptor | |
.GetParameters() | |
.Where(p => p.GetCustomAttributes<FromBodyAttribute>().Any()) | |
.Select(p => p.ParameterName) | |
.ToList()); | |
if (bodyParameter.Any(name => arguments.ContainsKey(name) && arguments[name] == null)) | |
{ | |
actionContext.Response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request body is empty."); | |
return; | |
} | |
if (!actionContext.ModelState.IsValid) | |
{ | |
actionContext.Response = request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment