Given the controller:
public class MyController : ApiController
{
public MyResponse Get([FromUri] MyRequest request)
{
// do stuff
}
}
And the model:
public class MyRequest
{
public Coordinate Point { get; set; }
// other properties
}
public class Coordinate
{
public decimal X { get; set; }
public decimal Y { get; set; }
}
And the API url:
/api/my?Point=50.71,4.52
I'd like the Point
property of the type Coordinate
to be converted from the querystring value 50.71,4.52
before reaching the controller.
Where can I hook in to the WebAPI to make it happen?
I've done a similar thing with a model binder. See option #3 of this article.
Your model binder would be something like this:
public class MyRequestModelBinder : IModelBinder {
public bool BindModel(HttpActionContext actionContext,
ModelBindingContext bindingContext) {
var key = "Point";
var val = bindingContext.ValueProvider.GetValue(key);
if (val != null) {
var s = val.AttemptedValue as string;
if (s != null) {
var points = s.Split(',');
bindingContext.Model = new Models.MyRequest {
Point = new Models.Coordinate {
X = Convert.ToDecimal(points[0],
CultureInfo.InvariantCulture),
Y = Convert.ToDecimal(points[1],
CultureInfo.InvariantCulture)
}
};
return true;
}
}
return false;
}
}
You must then wire it up into the model binding system in the action:
public class MyController : ApiController
{
// GET api/values
public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request)
{
return request;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With