You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法修改WCF寻址头a:To元素,添加后被端点地址覆盖

解决WCF中a:To头被端点地址覆盖的问题

问题场景

尝试修改WCF的a:To寻址头,但该元素在ClientMessageInspector的BeforeSendRequest方法中不可用;若在该方法中手动添加a:To头,其值会被端点地址覆盖。添加a:To头的代码如下:

var toHeader = MessageHeader.CreateHeader("To", "http://www.w3.org/2005/08/addressing", "https://toHeaderValue", true);
request.Headers.Add(toHeader);

当前使用的是CustomBinding,配置为SOAP 1.1版本、WS-Addressing 10版本,绑定代码如下:

{
    HttpTransportBindingElement bindingElement;
    var binding = new CustomBinding
    {
        Name = "*******",
        OpenTimeout = TimeSpan.FromMinutes(10),
        CloseTimeout = TimeSpan.FromMinutes(10),
        SendTimeout = TimeSpan.FromMinutes(10),
        ReceiveTimeout = TimeSpan.FromMinutes(10)
    };
    binding.Elements.Add(new TextMessageEncodingBindingElement
    {
        MessageVersion =
            MessageVersion.CreateVersion(EnvelopeVersion.Soap11,
                AddressingVersion.WSAddressing10),
        WriteEncoding = Encoding.UTF8
    });

    bindingElement = GetBindingElement(url);

    bindingElement.ManualAddressing = false;
    bindingElement.MaxReceivedMessageSize = 20000000;
    bindingElement.AllowCookies = false;
    bindingElement.BypassProxyOnLocal = false;
    bindingElement.MaxBufferSize = 20000000;
    bindingElement.TransferMode = TransferMode.Buffered;
    bindingElement.AuthenticationScheme = AuthenticationSchemes.Anonymous;
    bindingElement.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
    bindingElement.UseDefaultWebProxy = true;

    binding.Elements.Add(bindingElement);

    return binding;
}

private HttpTransportBindingElement GetBindingElement(string url)
{
    if (Uri.TryCreate(url, UriKind.Absolute, out var uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
        return new HttpTransportBindingElement();
    else
        return new HttpsTransportBindingElement();
}

问题原因

当HttpTransportBindingElement的ManualAddressing属性设为false时,WCF框架会自动使用端点地址填充a:To头,覆盖你在BeforeSendRequest中手动添加的值;同时,WS-Addressing 10规范下的a:To头由框架自动管理,因此在BeforeSendRequest方法中无法直接访问到该元素。

解决方案

将HttpTransportBindingElement的ManualAddressing属性设置为true,关闭WCF自动管理a:To头的行为,这样你就能在ClientMessageInspector的BeforeSendRequest方法中自由添加或修改a:To头,且不会被端点地址覆盖。

修改后的绑定代码关键行如下:

bindingElement.ManualAddressing = true; // 将原false改为true

注意:设置ManualAddressing = true后,需确保手动设置的a:To头值符合服务端要求,框架不再自动填充该字段。

内容的提问来源于stack exchange,提问作者Arjun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:45:33