Yar
Yar

Reputation: 7476

Converting the url to query string

So I am trying to convert this url which handled the POST reqs:

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

to its equavalent query string which is supposed to be:

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

but when I'm doing this I'm getting this error. Apparently it doesn't recognise one of the parameters:

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

This is the method that handles this Post request:

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

Any idea what's the problem?

Upvotes: 1

Views: 103

Answers (1)

Stinky Towel
Stinky Towel

Reputation: 778

The controller action doesn't know to look for the query string params. You have to define them explicitly.

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

Note this will break your first (RESTful) call example.

Upvotes: 2

Related Questions