Last active
September 25, 2017 00:08
-
-
Save gyuwon/20180505425529c9ec7f to your computer and use it in GitHub Desktop.
ValidateParametersAttribute.cs
This file contains 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
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