我正在尝试从网站调用我的 WCF 服务上的 POST 方法。然而,WCF 服务提示 json 字符串无效。
WCF 服务方法:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "reserve/batteries", BodyStyle = WebMessageBodyStyle.Bare)]
public bool ReserveBatteries(ReserveModel values)
从网站调用 POST 的方法:
var stations = TempData["Stations"];
string jsonStations = JsonHelper.SerializeJson(stations);
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:49288/reserve/batteries");
UTF8Encoding encoding = new UTF8Encoding();
string postData = "{\"Stations\": " + jsonStations;
postData += ", \"User\": \"" + User.Identity.Name + "\" }";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
我正在使用 Newtonsoft json 库进行序列化。 我尝试发送到我的服务的 json 字符串是:
{
"Stations": [
{
"BatteryStorages": null,
"CreatedDate": "2013-06-06T00:00:00+02:00",
"Description": "Aalborg City",
"Edges": [],
"ID": 3,
"IsActive": true,
"IsOperational": true,
"Reservations": [],
"StationLat": 57.02881,
"StationLong": 9.91777,
"StationMaintenances": [],
"StationType": null,
"Title": "Aalborg",
"TypeId": 1,
}
],
"User": "user1"
}
我已经用 JsonLint 验证了这一点它说这是一个有效的字符串。
WCF 接受的无效字符串(根据 JsonLint):
{
"Stations": "[
{
BatteryStorages:null,
CreatedDate:\"/Date(1370469600000+0200)/\",
Description:\"Aalborg City\",
Edges:[],
ID:\"3\",
IsActive:\"true\",
IsOperational:\"true\",
Reservations:[],
StationLat:\"57.02881\",
StationLong:\"9.91777\",
StationMaintenances:[],
StationType:null,
Title:\"Aalborg\",
TypeId:\"1\"
}
]",
"User": "user1"
}
WCF抛出的异常:
There was an error deserializing the object of type RestfulAPI.Resources.ReserveModel. End element 'Stations' from namespace '' expected. Found element 'item' from namespace ''.
这怎么可能?为什么 WCF 提示它无效,而 jsonlint(和其他人)说它无效。
编辑:
[DataContract]
public class ReserveModel
{
[DataMember]
public string Stations { get; set; }
[DataMember]
public string User { get; set; }
}
最佳答案
问题是您的模型对象的格式不正确。
要从您的 JSON 创建正确的 JSON 类,您可以使用 json2csharp或者如果你有,例如 VS2012 更新 2,你可以复制你的 JSON 并将 JSON 粘贴为类(编辑 ->选择性粘贴 > 将 JSON 粘贴为类)。
您必须记住,例如 DateTime 对象必须以 WCF 支持的某种方式传递。有关这方面的更多信息,请参见 here (msdn - WCF JSON serialization) .要避免这个问题,您只需将变量键入字符串并在以后转换它。
希望这对您有所帮助!
关于c# - WCF HttpPost 不是有效的 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769196/