我终于开始使用 WCF,但我遇到了另一个问题。发回的响应不包含 header
<?xml version="1.0" encoding="utf-8" ?>
我的服务契约(Contract)
[ServiceContract]
public interface IService1
{
// you can have optional parameters by simply specifying them and they will return null if there is nothing in there
[WebGet(UriTemplate="testing={value}", ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
XElement GetData(string value);
}
[XmlSerializerFormat]
public class Service1 : IService1
{
public XElement GetData(string value)
{
return new XElement("Somename", value);
}
}
返回这个(3 是指定的值)
<Somename>3</Somename>
是否也可以轻松地将响应包装在根元素中?类似
<response></response>
?
最佳答案
响应调用GetData方法的结果就是你在方法中返回的内容。如果你想要一个包装器,那么返回如下内容:
[XmlSerializerFormat]
public class Service1 : IService1
{
public XElement GetData(string value)
{
return new XElement("response",
new XElement("Somename", value));
}
}
编辑:
要添加 XML 声明(这实际上可能不是一个好主意,但您最了解),请执行以下操作:
var doc = new XDocument(
new XElement("response",
new XElement("Somename", value)));
doc.Declaration = new XDeclaration("1.0", "utf-8", "true");
return doc.Root;
关于WCF 响应省略了 <xml header>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782492/