客戶端發送的數據不會被反序列化。無法反序列化數組
客戶:
$.ajax({
type: 'POST',
dataType: "json",
url: 'savecommentsservice',
data: { "Pid": 0, "Comments": [{ "User": "bbbbbb", "Text": "aaaaaaaa" }, { "User": "ddddddd", "Text": "ccccccccc"}] },
DTO:
public class Comment
{
public string User { get; set; }
public string Text { get; set; }
}
public class SaveCommentsRequest
{
public int Pid { get; set; }
public string SiteId { get; set; }
public string Column { get; set; }
public List<Comment> Comments { get; set; }
}
服務器:
Routes.Add<SaveCommentsRequest>("/savecommentsservice");
...
public object Execute(SaveCommentsRequest request)
{
// Why is request.Comments null !!! All other params of the request works fine
// THe string I'm putting in is generated below - just to make sure its correct
request.Comments = new List<Comment>();
request.Comments.Add(new Comment { Text = "aaaaaaaa", User = "bbbbbb" });
request.Comments.Add(new Comment { Text = "ccccccccc", User = "ddddddd" });
var thisIsWhatIPutInto$AjaxCall = JsonSerializer.SerializeToString<SaveCommentsRequest>(request);
任何想法有什麼不對?爲什麼評論數組未填充。正如您從註釋中看到的,我使用servicestack json序列化器生成了字符串。
也許我在這裏錯過了一些隱藏的東西?
編輯 當小提琴手尋找什麼beeing傳遞我看到這一點:
POST http://localhost:4920/savecommentsservice HTTP/1.1
Host: localhost:4920
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: zh,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:4920/default.cshtml?viewId=3
Content-Length: 227
Cookie: ASP.NET_SessionId=slbw453revfgmwuuxyrim1an
Pragma: no-cache
Cache-Control: no-cache
SiteId=Site1&Pid=0&Column=C6&Comments%5B0%5D%5BUser%5D=bbbbbb&Comments%5B0%5D%5BText%5D=aaaaaaaa&Comments%5B1%5D%5BUser%5D=ddddddd&Comments%5B1%5D%5BText%5D=ccccccccc&Comments%5B2%5D%5BUser%5D=ggggggg&Comments%5B2%5D%5BText%5D=
而且在螢火蟲:
Parametersapplication/x-www-form-urlencoded
Column C6
Comments[0][Text] aaaaaaaa
Comments[0][User] bbbbbb
Comments[1][Text] ccccccccc
Comments[1][User] ddddddd
Comments[2][Text]
Comments[2][User] ggggggg
Pid 0
SiteId SiteId0
Source
SiteId=SiteId0&Pid=0&Column=C6&Comments%5B0%5D%5BUser%5D=bbbbbb&Comments%5B0%5D%5BText%5D=aaaaaaaa&Comments%5B1%5D%5BUser%5D=ddddddd&Comments%5B1%5D%5BText%5D=ccccccccc&Comments%5B2%5D%5BUser%5D=ggggggg&Comments%5B2%5D%5BText%5D=
問候
Larsi
嗨!首先,感謝一個偉大的框架。抱歉遲了迴應。將contentType設置爲application/json給了我一個例外:「類型定義應該以'{'開始,期望序列化類型'SaveCommentsRequest',得到的字符串以Pid = 0開頭並且註釋%5B0 ...」我應該在服務中改變任何東西? – Larsi 2012-03-13 07:27:19
嗨,剛剛意識到**數據**需要使用'JSON.stringify()'作爲JSON序列化,因爲jQuery不會自動爲您執行並將它發送到** application/x-www-form-urlencoded **默認情況下,即使您指定了JSON contentType,ContentType也是如此。無論如何修改工作的答案。 – mythz 2012-03-13 08:17:00