您可以为WCF使用的XmlWriter配置默认设置吗?

时间:2012-08-30 21:34:32

标签: wcf xmlwriter

在序列化数据时,有没有办法配置WCF服务与DataContractSerializer使用的默认XmlWriter?

使用DataContractSerializer开箱即用的WCF服务正在丢失新行(\ r \ n)。

[编辑:我为这种困惑道歉。开箱即用WCF不会丢失新行。]

我能够通过使用XmlWriterSettings(NewLineHandling.Entitize)使XmlWriter将新行编码为
,但我希望在序列化对象时使WCF的行为方式相同。

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;
       }
     }
  }

1 个答案:

答案 0 :(得分:1)

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

但我从未见过WCF丢失\r\n个字符 - 它正确地将\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字符。您能分享一下有关配置的更多细节(包括绑定)吗?