Skip to content

Instantly share code, notes, and snippets.

@gyuwon
Last active September 25, 2017 00:08
Show Gist options
  • Save gyuwon/20180505425529c9ec7f to your computer and use it in GitHub Desktop.
Save gyuwon/20180505425529c9ec7f to your computer and use it in GitHub Desktop.
ValidateParametersAttribute.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using static AttributeTargets;
[AttributeUsage(Class | Method, Inherited = true, AllowMultiple = false)]
public class ValidateParametersAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
foreach (HttpParameterBinding binding in
context.ActionDescriptor.ActionBinding.ParameterBindings)
{
HttpParameterDescriptor parameter = binding.Descriptor;
IEnumerable<ValidationAttribute> validations =
parameter.GetCustomAttributes<ValidationAttribute>() ??
Enumerable.Empty<ValidationAttribute>();
if (false == validations.Any())
continue;
string name = parameter.ParameterName;
object value = context.ActionArguments[name];
try
{
if (value == null)
{
foreach (ValidationAttribute v in validations)
v.Validate(value, name);
}
else
{
var validationContext = new ValidationContext(value);
foreach (ValidationAttribute v in validations)
v.Validate(value, validationContext);
}
}
catch (ValidationException exception)
{
context.Response = context.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, exception.Message);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment