ASP .Net Core Http [GET] for collection of nested objects

回眸只為那壹抹淺笑 提交于 2019-12-11 08:28:04

问题


I want to use a collection of nested objects in a query string like

public class Range 
{
  public decimal From {get;set},
  public decimal To {get;set}
} 

public class SearchParams 
{
  public IEnumerable<Range> Sizes {get;set;}
}

I know that better to use POST for this but I can't change an existing contract because of backward compatibility

So the question - Is there any option to pass it in a query string? or pass it as a string and to parse it in server


回答1:


Suppose you action method receives a SearchParams as parameter , which is named as para .

public IActionResult Index(SearchParams para)
{
    return new JsonResult(para);
}

you can send the GET request as below :

GET https://localhost:44386/?para.sizes[0].from=1.1&para.sizes[0].To=1.2&para.sizes[1].from=2.1&para.sizes[1].To=2.2& HTTP/1.1

Query String :

para.sizes[0].from=1.1&para.sizes[0].To=1.2&para.sizes[1].from=2.1&para.sizes[1].To=2.2

and the response will be :

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDIwMThcMTBcMTFcU08uR2V0Q29sbGVjdGlvblxBcHA=?=

{
  "sizes": [{
    "from": 1.1,
    "to": 1.2
  }, {
    "from": 2.1,
    "to": 2.2
  }]
}


来源:https://stackoverflow.com/questions/52756750/asp-net-core-http-get-for-collection-of-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!