【问题标题】:Can you configure default settings for the XmlWriter used by WCF?您可以为 WCF 使用的 XmlWriter 配置默认设置吗?
【发布时间】:2012-08-30 21:34:31
【问题描述】:

在序列化数据时,有什么方法可以通过 DataContractSerializer 配置 WCF 服务使用的默认 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;
       }
     }
  }

【问题讨论】:

    标签: wcf xmlwriter


    【解决方案1】:

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

    但我从未见过 WCF 丢失 \r\n 字符 - 它正确地将 \r 实体化为 &amp;#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 字符。您能否分享有关您的配置(包括绑定)的更多详细信息?

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      相关资源
      最近更新 更多