我正在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/

10-12 22:51