1

Is there any way to configure the default XmlWriter used by WCF service with DataContractSerializer when serializing data?

Out of the box WCF service using DataContractSerializer is losing the new lines (\r\n).

[Edit: I apologize for the confusion. Out of the box WCF DOES NOT lose the new lines.]

I am able to make XmlWriter encode the new lines to 
 by using XmlWriterSettings (NewLineHandling.Entitize), but I want to make WCF behave the same way when serialize my object.

public string Serialize<T>(T object)
  {
     var serializer = new DataContractSerializer(typeof(T));
     using (var stringWriter = new StringWriter())
     {
       var settings = new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize };
       using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
       {
          serializer.WriteObject(xmlWriter, object);
          string xml = stringWriter.ToString();
          return xml;
       }
     }
  }
4

1 回答 1

1

如果您想使用不同的XmlWriter,则需要使用自定义消息编码器。http://msdn.microsoft.com/en-us/library/ms751486.aspx上的示例显示了如何编写一个。

但我从未见过 WCF 丢失\r\n字符 - 它正确地将 in 实体化\r&#XD;至少在我检查的所有时间。当我运行下面的代码时,它显示正确返回的字符:

public class StackOverflow_12205872
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        string Echo(string text);
    }
    public class Service : ITest
    {
        public string Echo(string text)
        {
            return text;
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();
        string str = proxy.Echo("Hello\r\nworld");
        Console.WriteLine(str);
        Console.WriteLine(str[5] == '\r' && str[6] == '\n');

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

Fiddler 显示正在发送此请求:

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header></s:Header><s:Body><Echo xmlns="http://tempuri.org/"><text>Hello&#xD;
world</text></Echo></s:Body></s:Envelope>

响应还包含实体化的 CR 字符。您能否分享有关您的配置(包括绑定)的更多详细信息?

于 2012-08-30T21:56:32.027 回答