问题
I've written a very simple web service that returns an XML document.
The header for that document is currently
<?xml version="1.0" encoding="utf-8" ?>
and I would like it to return <?xml version="1.0" encoding="utf-16" ?>
How can I change the default output encoding in the .asmx or .cs file?
smo.asmx
<%@ WebService Language="C#" Class="smo" %>
smo.asmx
using <blah>
[WebService(Namespace="http://www.bl.uk/webservices/")]
public class smo : WebService
{
[XmlRoot(ElementName = "SQLServer")]
public class CDatabaseBackup
{
public string ServerName;
public string DatabaseCount;
}
//
// Generic SMO query processor
//
[WebMethod(Description = "WMIClassProperty: ", EnableSession = false, CacheDuration=60)]
public CDatabaseBackup smoDatabaseBackupStatus(string SQLServerName)
{
CDatabaseBackup result = new CDatabaseBackup();
Server svr;
<blah>
return result;
}
Ultimately this web service will be used within a SQL Server function and converted into an xml
data type. According to the documentation this needs to be UTF-16
.
alter
procedure monitor_sqlbackupaudit
as
begin
declare @l_xml_result nvarchar(max)
set @l_xml_result = ( select dbo.uspSMODatabaseBackup('sqlprod1vs') )
--set @l_xml_result = replace(@l_xml_result,'UTF-8','UTF-16');
declare @l_xml xml
set @l_xml = @l_xml_result
end
go
exec monitor_sqlbackupaudit
Msg 9402, Level 16, State 1, Procedure monitor_sqlbackupaudit, Line 15
XML parsing: line 1, character 38, unable to switch the encoding
回答1:
You can configure your web service to process UTF-16 instead of UTF-8 in the globalization section of Web.config. The requestEncoding and responseEncoding attributes of the globalization tag should be set to UTF-16.
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
must be converted to
<globalization requestEncoding="utf-16" responseEncoding="utf-16"/>
This change will allow the web service to output UTF-16, but it will also require the client to make its request in UTF-16.
来源:https://stackoverflow.com/questions/4146762/how-can-i-get-a-simple-c-sharp-web-service-to-return-xml-version-1-0-encodin