Skip to content

Instantly share code, notes, and snippets.

@enif-lee
Last active February 1, 2019 02:55
Show Gist options
  • Save enif-lee/6f315724e1782c61830666657751c3b8 to your computer and use it in GitHub Desktop.
Save enif-lee/6f315724e1782c61830666657751c3b8 to your computer and use it in GitHub Desktop.
ASP.NET MVC Empty Body Filter
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