gpt4 book ai didi

c# - 将二维数组传递给 Web API 服务器

转载 作者:行者123 更新时间:2023-11-30 17:54:58 27 4
gpt4 key购买 nike

我想发出如下所示的 Web Api 服务器请求:

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

如您所见,有一个坐标数组。每个坐标有两个点,我想提出这样的要求。我无法弄清楚我的 Web Api 路由配置应该是什么样子,以及方法签名应该是什么样子。

你能帮忙吗?谢谢!

最佳答案

最简单的方法可能是使用“包罗万象”的路由并在 Controller 操作中解析它。例如

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

关于c# - 将二维数组传递给 Web API 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15496834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com