簡體   English   中英

將二維數組傳遞給Web API服務器

[英]Passing two-dimentional array to Web API server

我想創建一個Web Api服務器請求,如下所示:

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

如您所見,有一系列坐標。 每個坐標有兩個點,我想提出這樣的請求。 我無法弄清楚我的Web Api Route Config應該是什么樣子,以及方法簽名應該如何。

你能救嗎? 謝謝 !

最簡單的方法可能是使用'catch-all'路由並在控制器操作中解析它。 例如

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

顯而易見的問題是,為什么您希望該信息在URL中? 它看起來像JSON更好地處理。

所以你可以做localhost:8080/GetByCoordinates/?jsonPayload={"coords": [[100,90],[180,90],[180,50],[100,50]]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM