将二维数组传递到 Web API 服务器

3
我希望进行一个Web Api服务器请求,格式如下:
localhost:8080/GetByCoordinates/[[100,90],[180,90],[180,50],[100,50]]

如您所见,这里有一个坐标数组。每个坐标都有两个点,我想要发起类似这样的请求。

我无法确定我的Web Api路由配置应该是什么样子,以及方法签名应该是什么形式。

您能帮忙吗?谢谢!


1
您的URI无效,您需要将其作为查询字符串或在正文中传递。 - cuongle
2个回答

1
最简单的方法可能是使用一个“捕获所有”路由并在控制器操作中解析它。例如:
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();
}

注意:我的解析代码仅作为示例提供。它比您要求的要宽容得多,您可能需要添加更多检查。
然而,更优雅的解决方案是使用自定义 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)
{
    ...
}

0
显而易见的问题是为什么你想把那些信息放在URL中?这看起来更适合使用JSON处理。
所以你可以使用 localhost:8080/GetByCoordinates/?jsonPayload={"coords": [[100,90],[180,90],[180,50],[100,50]]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接