我試圖手動發送一些XML內容到我創建的ASP MVC Web Api服務器。所述Controller.Put()方法是這樣的:ASP.NET MVC Web Api:application/xml PUT請求正文在服務器端爲空
public Game Put(int id, [FromBody] HttpAction[] actions)
{
Debug.WriteLine(actions[0].TargetId + ", " + actions[0].Type + ", " + actions[0].ContentType + ", " + actions[0].Contents);
Game game = this.provider.Update(id, actions);
return game;
}
的空引用檢查動作物體上的參數時立即發生。 這個方法接收的對象Id和類型HttpAction的陣列,其看起來像這樣:
[DataContract]
public class HttpAction
{
[DataMember]
public int TargetId { get; set; }
[DataMember]
public HttpActionType Type { get; set; }
[DataMember]
public HttpActionContentType ContentType { get; set; }
[DataMember]
public string Contents { get; set; }
}
我設置我的PUT請求是這樣的:
部首
- 內容 - 類型:application/xml
- 接受:*/*
- 接受編碼:gzip,deflate,sdch
- 接受語言:EN-GB,EN-US; Q = 0.8,連接; Q = 0.6
(最上面的是由我使用發送請求高級REST客戶端所產生的)
身體
<?xml version="1.0" encoding="utf-8"?>
<HttpActions>
<HttpAction>
<TargetId>0</TargetId>
<Type>Add</Type>
<ContentType>Player</ContentType>
<Contents>UnityPlayer</Contents>
</HttpAction>
</HttpActions>
在體內的另一種嘗試:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfHttpAction xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<HttpAction>
<TargetId xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">0</TargetId>
<Type xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">Add</Type>
<ContentType xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">Player</ContentType>
<Contents xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">UnityPlayer</Contents>
</HttpAction>
</ArrayOfHttpAction>
每當我發送這個請求時,我發現請求的主體在控制器中是空的。我設法使用JSON體測試它,它工作正常,我也在我的控制器上傳遞了HttpAction數組的單元測試,以檢查所有後臺代碼的正常工作。
我在爲請求構造XML時做錯了什麼?我讀過,我需要包括xmlns和xmlns:我但我不知道這些是什麼或設置它們。我嘗試了各種選擇,但沒有成功。
關鍵部分是數據契約模式。它應該有你的HttpAction類定義在哪裏的命名空間。 xmlns =「http:// schemas.datacontract.org/2004/07/ <在此輸入您的命名空間>」。我不知道如何讓評論不顯示這個鏈接,所以刪除多餘的空格。 – 2015-03-16 19:36:25
@Brian我在同一個數據合同的末尾嘗試了相同的數據合同,並且它工作正常 – 2015-03-17 03:16:15
如果在數據合同模式中未正確引用類的位置,那麼代碼不知道將數據序列化到什麼對象。在我的情況下,如果我剪切並粘貼你的例子,我仍然得到一個null,因爲我的類是在「SampleMVC.Controllers」命名空間中創建的。 @Ajay – 2015-03-17 13:27:24