问题
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¶.sizes[0].To=1.2¶.sizes[1].from=2.1¶.sizes[1].To=2.2& HTTP/1.1
Query String :
para.sizes[0].from=1.1¶.sizes[0].To=1.2¶.sizes[1].from=2.1¶.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