Created
April 19, 2015 08:05
-
-
Save Lucasus/6e335ee24536e53305f6 to your computer and use it in GitHub Desktop.
Custom binder for Validated<T> parameters for Web API 2, used in LucAdm
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
public static class BindingConfig | |
{ | |
public static void Register(HttpConfiguration config) | |
{ | |
config.ParameterBindingRules.Add(FindDescriptor); | |
} | |
private static HttpParameterBinding FindDescriptor(HttpParameterDescriptor descriptor) | |
{ | |
if (descriptor.ParameterType.IsGenericType && | |
descriptor.ParameterType.GetGenericTypeDefinition() == typeof (Validated<>)) | |
{ | |
return | |
(HttpParameterBinding) | |
Activator.CreateInstance( | |
typeof (PrimitiveBinder<>).MakeGenericType(descriptor.ParameterType.GetGenericArguments()[0]), | |
descriptor); | |
} | |
return null; | |
} | |
} | |
public class PrimitiveBinder<T> : HttpParameterBinding where T : struct | |
{ | |
public PrimitiveBinder(HttpParameterDescriptor descriptor) | |
: base(descriptor) | |
{ | |
} | |
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, | |
CancellationToken cancellationToken) | |
{ | |
var value = actionContext.RequestContext.RouteData.Values[Descriptor.ParameterName]; | |
var validatedPrimitive = Activator.CreateInstance(typeof (Validated<>).MakeGenericType(typeof (T)), value); | |
actionContext.ActionArguments[Descriptor.ParameterName] = validatedPrimitive; | |
var tsc = new TaskCompletionSource<object>(); | |
tsc.SetResult(null); | |
return tsc.Task; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment