.NET Standard 2.0客户端调用自定义绑定WCF服务遇授权问题求助
解决方案
1. 统一SOAP版本为SOAP 1.2
你的.NET Framework客户端使用MessageVersion.Soap12,而.NET Standard客户端用的是MessageVersion.Default(对应SOAP 1.1),这是核心差异。服务器可能仅支持SOAP 1.2格式的请求,导致认证逻辑未触发,返回匿名认证错误。修改编码绑定:
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8));
2. 确认HTTP头行为的实现正确性
确保AddHttpHeaderMessageEndpointBehavior的实现正确将Ocp-Apim-Subscription-Key添加到HTTP请求头中,典型实现如下:
public class AddHttpHeaderMessageEndpointBehavior : IEndpointBehavior { private readonly Dictionary<string, string> _headers; public AddHttpHeaderMessageEndpointBehavior(Dictionary<string, string> headers) { _headers = headers; } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ClientMessageInspectors.Add(new HttpHeaderMessageInspector(_headers)); } private class HttpHeaderMessageInspector : IClientMessageInspector { private readonly Dictionary<string, string> _headers; public HttpHeaderMessageInspector(Dictionary<string, string> headers) { _headers = headers; } public object BeforeSendRequest(ref Message request, IClientChannel channel) { var httpRequestMessage = request.Properties["httpRequest"] as HttpRequestMessageProperty; if (httpRequestMessage == null) { httpRequestMessage = new HttpRequestMessageProperty(); request.Properties.Add("httpRequest", httpRequestMessage); } foreach (var header in _headers) { httpRequestMessage.Headers[header.Key] = header.Value; } return null; } public void AfterReceiveReply(ref Message reply, object correlationState) { } } }
3. 调整SecurityBindingElement的SOAP 1.2兼容性
SOAP 1.2对安全头的格式有不同要求,确保SecurityBindingElement配置匹配SOAP 1.2:
var security = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); // 指定适配SOAP 1.2的安全版本 security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; security.IncludeTimestamp = true;
4. 验证APIM认证与WCF认证的顺序
Azure APIM会先验证Ocp-Apim-Subscription-Key,再将请求转发到后端WCF服务。确保你的HTTP头在请求最外层被正确发送,而非嵌套在SOAP消息体内。
完成以上调整后,重新创建通道工厂并调用服务,即可解决认证错误问题。
内容的提问来源于stack exchange,提问作者Dinesh
相关产品推荐
相关产品推荐

