WCF Change message encoding from Utf-16 to Utf-8

江枫思渺然 提交于 2021-02-07 10:10:58

问题


I have a WCF connected service in a .net core application. I'm using the code that is autogenerated taken the wsdl definition.

Currently at the top of the request xml is including this line:

<?xml version="1.0" encoding="utf-16"?>

I can't find a simple way to change this encoding to UTF-8 when sending the request.

Since I could find a configuration option a the request/client objects, I've tried to change the message with following code at IClientMessageInspector.BeforeSendRequest

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        // Load a new xml document from current request
        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(request.ToString());
        ((XmlDeclaration)xmlDocument.FirstChild).Encoding = Encoding.UTF8.HeaderName;

        // Create streams to copy 
        var memoryStream = new MemoryStream();
        var xmlWriter = XmlWriter.Create(memoryStream);

        xmlDocument.Save(xmlWriter);
        xmlWriter.Flush();
        xmlWriter.Close();
        memoryStream.Position = 0;
        var xmlReader = XmlReader.Create(memoryStream);

        // Create a new message
        var newMessage = Message.CreateMessage(request.Version, null, xmlReader);
        newMessage.Headers.CopyHeadersFrom(request);
        newMessage.Properties.CopyProperties(request.Properties);
        return null;
    }

But the newMessage object still writes the xml declaration using utf-16. I can see it while debugging at the watch window since.

Any idea on how to accomplish this (should be) simple change will be very apreciated.


回答1:


Which binding do you use to create the communication channel? The textmessageencoding element which has been contained in the CustomBinding generally contains TextEncoding property.
https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/textmessageencoding
WriteEncoding property specifies the character set encoding to be used for emitting messages on the binding. Valid values are

  • UnicodeFffeTextEncoding: Unicode BigEndian encoding
  • Utf16TextEncoding: Unicode encoding
  • Utf8TextEncoding: 8-bit encoding

The default is Utf8TextEncoding. This attribute is of type Encoding. As for the specific binding, it contains the textEncoding property too.
https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.basichttpbinding.textencoding?view=netframework-4.0
Feel free to let me know if there is anything I can help with.



来源:https://stackoverflow.com/questions/54837696/wcf-change-message-encoding-from-utf-16-to-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!