简体   繁体   中英

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 !

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)
{
    ...
}

The obvious question is why do you want that info to be in the URL? It looks like something that is better dealt with as JSON.

So you could do localhost:8080/GetByCoordinates/?jsonPayload={"coords": [[100,90],[180,90],[180,50],[100,50]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM