[英]Receive RESTClient POST JSON-Body in C# mvc and convert it to usable Data
我有一個結合了C#網站和Web API的移動Android應用程序。 在Mobile Android App中,我想發送帶有List<Integer>
, List<Double>
和long
的HttpPost到C#Web API,在C#Web API中,我想將其轉換回List<int>
, List<decimal>
及long
。
自從我之前做過以來,Android App的發送部分就很快完成了。 但是在C#Web API的接收端,我遇到了很多麻煩。
在一個Web API控制器中,我添加了以下方法:
[HttpPost]
[AllowAnonymous]
[ActionName("save")]
public bool SaveOrders([FromBody] STILL_UNDETERMINED parameter)
{
// TODO: Convert given parameter to usable List<int>, List<decimal> and long
}
現在,我正在使用FireFox的RESTClient插件發送以下HttpPOST:
Method: POST http://localhost:54408/api/orders/save
Header: Content-Type application/x-www-form-urlencoded
Body: {"newPrices":[0.4,7.4],"productIds":[20,25],"dateInTicks":1402459200000}
我確實可以使用上述方法進行調試,但是現在我需要將其轉換為List,List和long。
因此,我的問題是:
該方法應使用什么參數? 我試過了:
string
(始終為null); JObject
(出於某些未知原因,它替換了所有[
:" {"
,導致: { "{\\"newPrices\\":": { "0.4,7.4],\\"productIds\\":": { "20,25],\\"dateInTicks\\":1402459200000}": "" } } }
; dynamic
(我無法做任何事情,因為它已轉換為看似空的object
) 我應該如何將此參數轉換為List<int>
, List<decimal>
和long
?
自定義對象:
Data
{
public List<int> productIds { get; set; }
public List<decimal> newPrices { get; set; }
public long dateInTicks { get; set; }
}
從理論上講,它是如此簡單:
actions
對MapHttpRoutes進行一些更改)。 看起來很簡單,但我無法在C#中使用它。.在Java中,我會在不到30分鍾的時間內完成此操作,而且我可以通過Google-ing找到很多有用的答案,但是當我使用Google for C#HttpPOSTs時我只得到結果,要么從C#發送HttpPOST,要么在發送HttpPOST之后從流中讀取響應。.僅僅是從C#mvc中的[HttpPost]
方法接收HttpPOST的JSON主體。
PS:我的配置文件中包含以下內容,僅接收JSON格式的響應,這可能是錯誤的。
// Only allow JSON response format
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
將JSON數據發布到MVC Action時,您需要將Content-Type
標頭指定為application/json
。 如果不這樣做,則除了傳遞標准表單集合外,如果傳遞其他任何內容,則模型將始終為null。
[HttpPost]
[AllowAnonymous]
[ActionName("save")]
public bool SaveOrders(Data model)
{
//model is populated, and you have access to ModelState
}
public class Data
{
// the JSON to Model mapper match is case-insensitive
public List<int> ProductIds { get; set; }
public List<decimal> NewPrices { get; set; }
public long DateInTicks { get; set; }
}
發布數據:
{"newPrices":[0.4,7.4],"productIds":[20,25],"dateInTicks":1402459200000}
因此,您應該能夠將其作為模型對象傳遞。 首先設置您的模型類:
public class Order
{
public List<int> productIds { get; set; }
public List<decimal> newPrices { get; set; }
public long dateInTicks { get; set; }
}
然后設置您的操作以使用模型綁定到:
[HttpPost]
public ActionResult SaveOrders(Order order)
{
//TODO: Save...
}
然后,您要做的就是確保將其作為與Order模型匹配的JSON對象發送。 因此,發布值將為[“ productIds”],[“ newPrices”]等,並且它將自動在SaveOrders上填充order參數。 這給這些東西如何綁定提供了一個好主意:
http://weblogs.asp.net/nmarun/asp-net-mvc-2-model-binding-for-a-collection
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.