【问题标题】:Web API not parsing get parameters correctlyWeb API 未正确解析获取参数
【发布时间】:2017-05-26 19:04:49
【问题描述】:

我有以下网址

    http://localhost/api/map/tmc/identify?
    geometry={x:-112.0469856262207,y:33.3926093953406, spatialReference:{wkid:4326}}
    &geometryType=esriGeometryPoint
    &mapExtent={xmin:-112.18062400817871,ymin:33.33956359362892,xmax:-111.95076942443848,ymax:33.49201883920683, spatialReference:{wkid:4326}}
    &tolerance=5
    &sr=4326
    &imageDisplay=1340,1065,96
    &layers=all:0
    &returnGeometry=true
    &returnM=false

我正在尝试使用以下操作拦截该对象

    public class SpatialReference
    {
        public int wkid { get; set; }
    }

    public class Geometry
    {
        public double x { get; set; }
        public double y { get; set; }
        public SpatialReference spatialReference { get; set; }
    }

    public class MapExtent
    {
        public double xmin { get; set; }
        public double ymin { get; set; }
        public double xmax { get; set; }
        public double ymax { get; set; }
        public SpatialReference spatialReference { get; set; }
    }

    public class RootObject
    {
        public Geometry geometry { get; set; }
        public string geometryType { get; set; }
        public MapExtent mapExtent { get; set; }
        public int tolerance { get; set; }
        public int sr { get; set; }
        public List<int> imageDisplay { get; set; }
        public string layers { get; set; }
        public bool returnGeometry { get; set; }
        public bool returnM { get; set; }
    }

    [HttpGet]
    [Route("api/map/tmc/identify")]
    public object Identify([FromUri]RootObject root)
    {
        return root;
    }

我回来了

{  
   "geometry":{  
      "x":0.0,
      "y":0.0,
      "spatialReference":null
   },
   "geometryType":"esriGeometryPoint",
   "mapExtent":{  
      "xmin":0.0,
      "ymin":0.0,
      "xmax":0.0,
      "ymax":0.0,
      "spatialReference":null
   },
   "tolerance":5,
   "sr":4326,
   "imageDisplay":[  
      0
   ],
   "layers":"all:0",
   "returnGeometry":true,
   "returnM":false
}

如您所见,公差和 sr 已正确设置,但对象未正确设置。不幸的是,我无法控制请求(它始终是 GET 并且采用这种格式)。如何正确地将 url 解析为正确的对象

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api2


    【解决方案1】:

    由于您的 http GET 中有 9 个查询参数,您应该在操作方法中声明 9 个参数而不是根对象,即:

    [HttpGet]
    [Route("api/map/tmc/identify")]
    public object Identify([FromUri]Geometry geometry, 
        [FromUri]string geometryType, 
        [FromUri] MapExtent mapExtent,
        ...)
    

    [FromUri]RootObject root 不会正确映射参数,因为它们是查询参数并且不是 POST 正文

    【讨论】:

    • 我最初尝试过这个,它说Can't bind multiple parameters 把我带到了stackoverflow.com/questions/38715230/…,它说要使用一个根对象,但又是一个帖子。我刚刚尝试了尝试[FromUri] Geometry geometry,但我仍然收到{ "x": 0, "y": 0, "spatialReference": null }
    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多