Skip to content

Instantly share code, notes, and snippets.

@Lucasus
Created April 19, 2015 08:05
Show Gist options
  • Save Lucasus/6e335ee24536e53305f6 to your computer and use it in GitHub Desktop.
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
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