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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Does it work with asp.net core 1.0? (I'm still a bit lost with all this versions)
If you use .Net Core you should use MVC 6 instead of Web Api 2
After doing some research and talk with some colleagues this is the best option. this actually worked out so thank you.
1

You can call your api by doing this:

api/locations?lat=xxx&lng=zzz

2 Comments

made an edit to my question. but the problem is that I cannot change how the request is made.
You may need to implement a custom IModelBinder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.