我正在尝试创建一个ClientInspector,它将向传出的SOAP请求添加一些数据,并将其添加为客户端服务的端点行为。像这样:
public class InsertHeaderClientInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
{
var HeaderData = new ProcType()
{
attr = _correlation
};
MessageHeader header = MessageHeader.CreateHeader("HeaderInfo", "http://schemas.tempuri.fi/process/2016/04/", HeaderData);
request.Headers.Add(header);
return null;
}
}
[System.Xml.Serialization.XmlRootAttribute("HeaderInfo", Namespace = "http://schemas.tempuri.fi/process/2016/04/", IsNullable = false)]
public class ProcType
{
[XmlElement(Namespace = "")]
public string attr;
}
Inspector工作正常,但问题是生成的SOAP消息将具有ProcType.attr的命名空间,我想删除它。
<s:Header>
<HeaderInfo xmlns="http://schemas.tempuri.fi/process/2016/04/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<attr xmlns="http://schemas.datacontract.org/2004/07/MyService.Behaviors">asdasd</attr>
</HeaderInfo>
</s:Header>
相反它应该像
<s:Header>
<HeaderInfo xmlns="http://schemas.tempuri.fi/process/2016/04/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<attr">asdasd</attr>
</HeaderInfo>
</s:Header>
我尝试使用的XMLElement属性不起作用。那么如何删除这个不必要的命名空间呢?
答案 0 :(得分:2)
我最后通过创建我要插入的自定义标头元素来解决此问题。
public class ProcessGuidHeader : MessageHeader
{
private string _attr;
private string _headerName = "HeaderInfo";
private string _elementName = "ProcType";
private string _headerNamespace = "http://schemas.tempuri.fi/process/2016/04/";
public ProcessGuidHeader(string attr)
{
_attr = attr;
}
public string Attr
{
get { return _attr; }
}
public override string Name
{
get { return _headerName; }
}
public override string Namespace
{
get { return _headerNamespace; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteElementString(_elementName, _attr);
}
}
这不会为header子元素设置任何名称空间并解决问题。