1

Got an app that makes Get requests with some parameters to my old api now I want to make a new api using .Net MVC6 but I cannot change all the clients for them to use a different Uri.

I need to make my new api compatible with those kind of requests.The query style is this: localhost/api/locations?location[lat]=12&location[lng]=21

public class Location
{
    public string lat;
    public string lng;
}

[Route("api/[controller]")]
public class LocationsController : Controller
{        
    [HttpGet]
    public ActionResult Get(Location loc)
    { 
        var av=   new CreatedAtActionResult("","",null,null);
        return av;
    }
}

My question is, how can I bind this "kind" of query to the parameter?

tereško
  • 57,247
  • 24
  • 95
  • 149
Miguel de Sousa
  • 224
  • 2
  • 15

2 Answers2

3

The easy thing to do would be to override the parameters names:

public ActionResult Get([FromUri(Name = "location[lat]")]string lat, [FromUri(Name = "location[lng]")]string lng)
{
}

Alternativelly you could implement a custom TypeConverter or ModelBinder.

You could find a nice overview of all the different possibilities here: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api


Update: I've found a similar question on Changing the parameter name Web Api model binding

Community
  • 1
  • 1
AleFranz
  • 761
  • 1
  • 7
  • 13
1

You can call your api by doing this:

api/locations?lat=xxx&lng=zzz

Ric
  • 12,371
  • 3
  • 26
  • 36