我需要使用HTTPClient调用WCF端点,我已经找到了如何做到这一点。我遇到的问题是,我不知道如何对XML序列化程序进行编码,以生成有效的内容字符串。
在我的代码中,我有以下类型:
public class MyParameters
{
public string source { get; set; }
public string key { get; set; }
public string secret { get; set; }
public TimeSpan lockExpirationTime { get; set; }
}
我把它序列化成这样:
var input = new MyParameters
{
source = "some source",
key = "some key",
secret = "some secret",
lockExpirationTime = new TimeSpan(0, 0, 10)
};
var serializer = new XmlSerializer(typeof(MyParameters));
var stringwriter = new System.IO.StringWriter();
serializer.Serialize(stringwriter, input);
var xml = stringwriter.ToString();
最终结果是这个xml字符串:
<?xml version="1.0" encoding="utf-16"?>
<MyParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<source>some source</source>
<key>some key</key>
<secret>some secret</secret>
<lockExpirationTime>PT10S</lockExpirationTime>
</MyParameters>
但是,为了让WCF端点满意而不返回Bad Request结果,xml需要看起来像这样:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<MyParameters xmlns="http://tempuri.org/">
<source>some source</source>
<key>some key</key>
<secret>some secret</secret>
<lockExpirationTime>PT10S</lockExpirationTime>
</MyParameters>
</s:Body>
</s:Envelope>
如何让序列化程序给我这个结果?我正在使用.Net Core 3.1
谢谢。
尝试xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version="1.0" encoding="utf-8" ?>" +
"<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">" +
"<s:Body>" +
"</s:Body>" +
"</s:Envelope>";
XDocument doc = XDocument.Parse(xml);
XNamespace sNs = doc.Root.GetNamespaceOfPrefix("s");
XElement body = doc.Descendants(sNs + "Body").FirstOrDefault();
string source = "some source";
string key = "some key";
string secret = "secret";
string lockExpirationTime = "PT10S";
XNamespace def = "http://tempuri.org/";
XElement myParameters = new XElement(def + "MyParameters");
body.Add(myParameters);
myParameters.Add(new object[] {
new XElement(def + "source", source),
new XElement(def + "key", key),
new XElement(def + "secret", secret),
new XElement(def + "lockExpirationTime", lockExpirationTime)
});
string xmlStr = doc.ToString();
}
}
}