3

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 !

1
  • 1
    Your URI is not valid, you need to pass as query string or in body Commented Mar 19, 2013 at 10:28

2 Answers 2

1

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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]]}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.