[英]Can C# Web API Deserialize Object in URI that Contains a Dictionary
我正在嘗試在GET請求中傳遞復雜的對象。 C#模型對象如下所示:
public class GetRequest
{
public string ID { get; set; }
public List<string> RequestedFields { get; set; }
public Dictionary<string, List<string>> RequestedGrids { get; set; }
}
查看Chrome中的請求,我在“查詢字符串參數”下看到以下內容:
ID: 1
RequestedFields[]: someTxtField
RequestedFields[]: someOtherField
RequestedGrids[someGrid][]: keyColumn
RequestedGrids[someGrid][]: someDataColumn
我希望這樣的請求可以正確反序列化為以下操作中的參數:
[HttpGet]
[ActionName("get")]
public Dictionary<string,object> GetStuff([FromUri] GetRequest get_req)
但是,每當請求進入此操作時,參數的RequestedGrids屬性始終計數為0,而其他屬性則填充良好。 有沒有辦法使這項工作?
加成
進入JQuery $ .get調用的對象如下所示:
{ ID: p_key, RequestedFields: p_page.dataIds, RequestedGrids: p_page.grids }
其中,RequestedFields是純字符串數組,RequestedGrids是純對象,其中每個對象屬性值都是字符串數組。
當您需要發送大量數據(尤其是復雜數據)時,最好將數據作為POST請求正文的一部分發送。 這樣,您可以確保結構完全匹配,並且可以輕松地與JSON格式進行轉換。
輸入在GET上是什么樣的? 字典類型通常很難進行反序列化 -有關詳細信息,請參見將JSON字符串反序列化為Dictionary <string,object> 。
完成此操作的最簡單方法似乎是只傳遞JSON查詢字符串,而不使用自動綁定。 所以動作看起來像這樣:
[HttpGet]
[ActionName("get")]
public Dictionary<string, object> GetStuff(string get_str)
{
var get_req = JsonConvert.DeserializeObject<GetRequest>(get_str);
//Do ur stuff
}
JS看起來像這樣:
$.get('<action path>', { get_str: JSON.stringify(get_obj) }, ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.