WebAPI: Display Custom Settings

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 API url:

 /api/my?Point=50.71,4.52 

I want the Point property of type Coordinate be converted from a querystring value of 50.71,4.52 before reaching the controller.

Where can I connect to WebAPI for this to happen?

+7
c # asp.net-web-api model-binding
source share
1 answer

I did a similar thing with a model binder. See Option # 3 in this article .

Your connecting device will look 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; } } 

Then you must connect it to the modelโ€™s binding system to the action:

 public class MyController : ApiController { // GET api/values public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request) { return request; } } 
+2
source share

All Articles