Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI: custom parameter mapping

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?

like image 255
David Avatar asked Aug 12 '13 15:08

David


1 Answers

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;
    }
}
like image 100
ssarabando Avatar answered Oct 02 '22 15:10

ssarabando