2017-05-05 87 views
1

所以我想这个网址该处理的POST请求数转换:转换的URL,查询字符串

// this works 
http://localhost/api/locations/postlocation/16/555/556 

,其被认为是其equavalent查询字符串:

http://localhost/api/locations/postlocation?id=16&lat=88&lon=88 

但是当我正在做这个我得到这个错误。显然,它不承认的参数之一:

"Message": "An error has occurred.", 
    "ExceptionMessage": "Value cannot be null.\r\nParameter name: entity", 
    "ExceptionType": "System.ArgumentNullException", 

这是处理这个帖子请求的方法:

[Route("api/locations/postlocation/{id:int}/{lat}/{lon}")] 
public IHttpActionResult UpdateUserLocation(string lat, string lon, int id) 
{ 
    if (!ModelState.IsValid) 
    { 
     return BadRequest(ModelState); 
    } 
    var user = db.Users.FirstOrDefault(u => u.Id == id); 

    if (user == null) 
    { 
     return NotFound(); 
    } 

    var userId = user.Id; 

    var newLocation = new Location 
    { 
     Latitude = Convert.ToDouble(lat), 
     Longitude = Convert.ToDouble(lon), 
     User = user, 
     UserId = user.Id, 
     Time = DateTime.Now 
    }; 

    var postLocation = PostLocation(newLocation); 

    return Ok(); 
} 

任何想法有什么问题呢?

回答

2

控制器操作不知道查找查询字符串参数。你必须明确地定义它们。

[Route("api/locations/postlocation")] 
public IHttpActionResult UpdateUserLocation([FromUri] int id, [FromUri] string lat, [FromUri] string lon) 

请注意,这将打破您的第一个(RESTful)调用示例。

+1

如果同时添加'Route's,那么它不会破坏第一个示例。 –