将url转换为查询字符串

时间:2017-05-05 18:09:49

标签: c# asp.net rest

所以我试图转换这个处理POST reqs的网址:

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

到它的等价查询字符串,应该是:

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",

这是处理此Post请求的方法:

[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();
}

知道问题是什么?

1 个答案:

答案 0 :(得分:2)

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

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

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