我似乎在StackOverflow的其他地方找不到答案,所以我现在要问它。
我正在尝试在API中测试更新的PUT,以将答案数据从Wordpress网站提交到我们的数据库。该API作为WP和SQL之间的中介。
我的课:
[DataContract]
public class WordpressAnswerEntry
{
/// <summary>
/// Gets or sets the ID of the question the user is submitting an answer for
/// </summary>
[DataMember]
public string QuestionID { get; set; }
/// <summary>
/// Gets or sets the data they're submitting
/// </summary>
[DataMember]
public string AnswerData { get; set; }
}
简单容易。我试过了int QuestionID和字符串
我的方法:
[AcceptVerbs("PUT")]
[Route("api/Questions/{applicationID}/{groupID}")]
public HttpResponseMessage Put([FromBody] IEnumerable<WordpressAnswerEntry> answerlist, int applicationID = 0, int groupID = 0)
同样,没什么特别的。我已经尝试过将其作为列表和自定义集合类。 IEnumerable是我最后的尝试。
我在API中有一个索引页,可用于提交测试并查看返回的JSON。下面是我的测试用例:
$("#TestQuestionsWithAnswersButton").click(function (e) {
e.preventDefault();
var answerEntries = {
answers:
[
{ QuestionID: "14",
AnswerData: "first name" },
{ QuestionID: "15",
AnswerData: "last name" },
{ QuestionID: "16",
AnswerData: "email here" },
{ QuestionID: "25",
AnswerData: "12"
},
]
}
var answerlist = {
answers: answerEntries
};
$.ajax({
type: "PUT",
url: "api/Questions/0/96",
data: JSON.stringify(answerlist),
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function (data) {
$("#ResponseDiv").html(JSON.stringify(data));
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
我已经尽一切努力使它起作用。我已经尝试过是否封装“ answerList”。我已经尝试过和没有stringfy。我已经尝试过使用{answerlist:answerEntries},也可以不使用stringfy。我已经尝试过使用[DataMember]和[DataContract]。我设置了内容类型。我有类型设定。我不知道该怎么办
每个测试每次都为答案列表返回null,并且没有失败。我不知道该怎么办。在确认可以正常工作之前,我无法发布它,但是由于它无法正常工作,我无法确认它。我可以告诉它正确的路由,因为命中了断点(我得到了400,当答案为空时我有意返回),但是由于某种原因,我无法转换此JSON数组。
最佳答案
与其将数组添加到一个对象然后将该对象添加到另一个对象,不如通过以下方式发送字符串化数组:
var answers =
[
{ QuestionID: "14",
AnswerData: "first name" },
{ QuestionID: "15",
AnswerData: "last name" },
{ QuestionID: "16",
AnswerData: "email here" },
{ QuestionID: "25",
AnswerData: "12"
}
];
然后在你的ajax中:
data: JSON.stringify(answers)