Skip to content

Instantly share code, notes, and snippets.

@mstum
Created October 4, 2012 08:44
Show Gist options
  • Save mstum/3832307 to your computer and use it in GitHub Desktop.
Save mstum/3832307 to your computer and use it in GitHub Desktop.
Model Binder for Byte Arrays
public class AnnounceResultModelBinder : IModelBinder
{
private ByteArrayModelBinder _byteBinder = new ByteArrayModelBinder();
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelName == "info_hash" || bindingContext.ModelName == "peer_id")
{
var query = controllerContext.RequestContext.HttpContext.Request.Url.Query;
if (query.StartsWith("?")) query = query.Substring(1);
var parts = query.Split('&')
.Select(pq => { var ix = pq.IndexOf('='); return new string[] { pq.Substring(0, ix), pq.Substring(ix + 1) }; })
.FirstOrDefault(pq => string.Equals(pq[0], bindingContext.ModelName));
var value = parts[1];
return HttpUtility.UrlDecodeToBytes(value);
}
else
{
return _byteBinder.BindModel(controllerContext, bindingContext);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment