Reputation: 843
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 !
Upvotes: 3
Views: 283
Reputation: 149020
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)
{
...
}
Upvotes: 1
Reputation: 7814
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]]}
Upvotes: 0