如何在.NET WCF中显式设置soap消息头元素命名空间 [英] How to set soap message header element namespace explicitly in .NET WCF
问题描述
我正在尝试创建一个 ClientInspector,它将向传出的 SOAP 请求添加一些数据,并将其添加为客户端服务的端点行为.像这样:
I'm trying to create a ClientInspector that will add some data to outgoing SOAP requests and add it as a endpoint behavior for client services. Something like this:
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 的命名空间,我想将其删除.
Inspector is working fine, but the problem is that generated SOAP message will have namespace for ProcType.attr and I want to remove it.
<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 属性不起作用.那么如何删除这个不必要的命名空间?
XMLElement attribute I've tried to use does not work. So how do I remove this unnecessary namespace?
推荐答案
我最终通过创建自定义标题元素来解决这个问题.
I ended up fixing this issue by creating custom header element which I insert to request.
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);
}
}
这不会为标题子元素设置任何命名空间并解决了问题.
This does not set any namespace for header child element and solves the issue.
这篇关于如何在.NET WCF中显式设置soap消息头元素命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!