在获取从客户端发送到服务器上的WCF服务的base64编码字符串时,我遇到了一些奇怪的问题。在我的WCF服务方法中,此字符串始终为null。我所拥有的商务舱是:
[DataContract(Namespace = "")]
public class Test
{
[DataMember]
public int Id { get; set; }
[DataMember]
public int Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string MyString { get; set; }
}
我将xml中的发布数据发送到我的WCF服务:
string data = string.Format("<Test><Id>{0}</Id><Name>{1}</Name><Age>{2}</Age><MyString>{3}</MyString></Test>",
1, "name", 20, Convert.ToBase64String(image));//image is in bytes
以上&#34;图像&#34;以字节为单位。
在MyTestService.svc.cs中的服务器上接收客户端数据时:
public void CreateTest(Test test)
{
在&#34;测试&#34;对象我得到了我从客户端发送的所有属性的值,除了&#34; MyString&#34;属性。它总是无效。我仔细检查了Fiddler&#34; MyString&#34; xml中的tag包含base64编码的字符串。你能帮我解决这个问题吗?
xml标记中的属性值长度是否有限制。编码的图像字符串足够长。
答案 0 :(得分:2)
DataContractSerializer
(WCF的默认序列化程序)强制执行数据协定中元素的顺序。如果未使用Order
属性的[DataMember]
属性明确指定顺序,则默认顺序为字母顺序。尝试按该顺序发送请求(Age,Id,MyString,Name),您应该看到正确填充了MyString的值。
public class StackOverflow_12693581
{
[DataContract(Namespace = "", Name = "Test")]
public class TestData
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string MyString { get; set; }
}
[ServiceContract]
public interface ITest
{
[OperationContract]
void Process(TestData test);
}
public class Service : ITest
{
public void Process(TestData test)
{
Console.WriteLine("MyString: {0}", test.MyString ?? "<<NULL>>");
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
byte[] image = Enumerable.Range(1, 100).Select(i => (byte)i).ToArray();
WebClient c = new WebClient();
Console.WriteLine("Order as in the question");
string data = string.Format("<Test><Id>{0}</Id><Name>{1}</Name><Age>{2}</Age><MyString>{3}</MyString></Test>",
1, "name", 20, Convert.ToBase64String(image));//image is in bytes
c.Headers[HttpRequestHeader.ContentType] = "text/xml";
c.UploadString(baseAddress + "/Process", data);
Console.WriteLine();
c = new WebClient();
Console.WriteLine("Correct order");
data = string.Format("<Test><Age>{2}</Age><Id>{0}</Id><MyString>{3}</MyString><Name>{1}</Name></Test>",
1, "name", 20, Convert.ToBase64String(image));//image is in bytes
c.Headers[HttpRequestHeader.ContentType] = "text/xml";
c.UploadString(baseAddress + "/Process", data);
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}