我在 WebServiceHost 中使用 WCF .NET 4.0 托管。Normaly 一切正常,直到我在类中使用我自己定义的类数组。
服务器端功能
[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 不知道如何反序列化它或有任何其他错误?