【问题标题】:Complex object in ASP.NET WEB API 2ASP.NET WEB API 2 中的复杂对象
【发布时间】:2016-03-25 18:49:10
【问题描述】:

有一个应用程序向我的旧 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;
    }
}

我的问题是,如何将这种“类型”的查询绑定到参数?

【问题讨论】:

    标签: c# asp.net-core-mvc


    【解决方案1】:

    简单的做法是覆盖参数名称:

    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发现了一个类似的问题

    【讨论】:

    • 它是否适用于 asp.net core 1.0? (我仍然对所有这些版本有点迷失)
    • 如果你使用 .Net Core 你应该使用 MVC 6 而不是 Web Api 2
    • 在做了一些研究并与一些同事交谈后,这是最好的选择。这实际上解决了,所以谢谢你。
    【解决方案2】:

    你可以这样调用你的api:

    api/locations?lat=xxx&lng=zzz

    【讨论】:

    • 对我的问题进行了编辑。但问题是我无法更改请求的发出方式。
    • 你可能需要实现一个自定义的IModelBinder
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2014-02-27
    • 2019-01-27
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多