Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing two-dimentional array to Web API server

I would like to make a Web Api server request that looks like this :

localhost:8080/GetByCoordinates/[[100,90],[180,90],[180,50],[100,50]]

As you can see, there is an array of coordinates. each coordinate has two points, and i would like to make a request like this. I cannot figure out how my Web Api Route Config should look like, and how the method signature should be.

Can you help out ? thanks !

like image 531
Lironess Avatar asked Jul 31 '26 07:07

Lironess


1 Answers

The easiest way might be to use a 'catch-all' route and parse it in the controller action. For example

config.Routes.MapHttpRoute(
            name: "GetByCoordinatesRoute",
            routeTemplate: "/GetByCoordinatesRoute/{*coords}",
            defaults: new { controller = "MyController", action = "GetByCoordinatesRoute" }

public ActionResult GetByCoordinatesRoute(string coords)
{
    int[][] coordArray = RegEx.Matches("\[(\d+),(\d+)\]")
                              .Cast<Match>()
                              .Select(m => new int[] 
                                      {
                                          Convert.ToInt32(m.Groups[1].Value),
                                          Convert.ToInt32(m.Groups[2].Value)
                                      })
                              .ToArray();
}

Note: my parsing code is supplied just as an example. It's a lot more forgiving that what you asked for, and you probably need to add a more checks to it.

However, a more elegant solution would be to use a custom IModelBinder.

public class CoordinateModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        int[][] result;
        // similar parsing code as above
        return result;
    }
}

public ActionResult GetByCoordinatesRoute([ModelBinder(typeof(CoordinateModelBinder))]int[][] coords)
{
    ...
}
like image 147
p.s.w.g Avatar answered Aug 01 '26 20:08

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!