有一个应用程序向我的旧 api 发出带有一些参数的 Get 请求,现在我想使用 .Net MVC6 制作一个新的 api,但我无法更改所有客户端以使用不同的 Uri。
我需要让我的新 api 与这些请求兼容。查询样式是这样的: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;
}
}
我的问题是,如何将这种“种类”的查询绑定(bind)到参数?
请您参考如下方法:
最简单的做法是覆盖参数名称:
public ActionResult Get([FromUri(Name = "location[lat]")]string lat, [FromUri(Name = "location[lng]")]string lng)
{
}
或者,您可以实现自定义 TypeConverter 或 ModelBinder。
你可以在这里找到所有不同可能性的一个很好的概述: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
更新: 我在 Changing the parameter name Web Api model binding 上发现了类似的问题
