简体   繁体   English

ASP.NET WEB API 2中的复杂对象

[英]Complex object in ASP.NET WEB API 2

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. 现在有一个应用程序向我的旧api发出带有一些参数的Get请求,我想使用.Net MVC6制作一个新的api,但是我无法更改所有客户端以使其使用不同的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 我需要使新的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;
    }
}

My question is, how can I bind this "kind" of query to the parameter? 我的问题是,如何将查询的这种“种类”绑定到参数?

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. 或者,您可以实现自定义TypeConverter或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 您可以在这里找到所有不同可能性的不错概述: 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 更新:我发现了关于更改参数名称Web Api模型绑定的类似问题

您可以通过以下方式调用您的api:

api/locations?lat=xxx&lng=zzz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM