我在 WebServiceHost 中使用 WCF .NET 4.0 托管。通常一切正常,直到我在类中使用我自己定义的类数组。
服务端函数
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "foo")]
[OperationContract]
void Foo(FooQuery query);
类
[DataContract(Namespace="")]
public class FooQuery
{
[DataMember]
public MyFoo[] FooArray;
}
[DataContract(Namespace = "")]
public class MyFoo
{
[DataMember]
public string[] items;
}
客户端:
//create object
FooQuery myOriginalFoo = new FooQuery();
MyFoo _myFoo = new MyFoo();
_myFoo.items = new string[] { "one", "two" };
myOriginalFoo.FooArray = new MyFoo[] { _myFoo };
//serialize
var json = new JavaScriptSerializer().Serialize(myOriginalFoo);
string _text = json.ToString();
//output:
// {"FooArray":[{"items":["one","two"]}]}
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:2213/foo");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(_text);
streamWriter.Flush();
streamWriter.Close();
}
//here server give back: 400 Bad Request.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
我还尝试使用 System.Runtime.Serialization.Json.DataContractJsonSerializer 操作我的类 - 一切正常,直到我发送到服务器并且 webinvoke 返回错误 400。为什么 webInvoke 不知道如何反序列化它或有任何其他错误?
最佳答案
我发现名为 CollectionDataContract 的魔法属性是个把戏。
添加新的集合类:
[CollectionDataContract(Namespace = "")]
public class MyFooCollection : List<MyFoo>
{
}
更改查询类
[DataContract(Namespace="")]
public class FooQuery
{
[DataMember]
public /*MyFoo[]*/MyFooCollection FooArray;
}
客户端代码更改:
MyFooCollection _collection = new MyFooCollection();
_collection.Add(_myFoo);
myOriginalFoo.FooArray = _collection; //new MyFoo[] { _myFoo };
现在所有变量都序列化了:)是的..需要很多时间才能弄清楚。
关于c# - WCF WebInvoke JSON 反序列化失败 - 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19785116/