.NET Core中通过HTTP头实现SOAP调用Basic认证报错求助
问题核心原因
你之前的写法把Basic认证所需的Authorization字段加到了SOAP消息头里,而非HTTP请求头中。服务端会从HTTP请求头读取认证信息,自然识别不到你的凭据,所以返回了匿名访问未授权的报错。
解决方案
方案1:使用WCF原生Basic认证配置(推荐)
直接配置绑定的安全策略,由框架自动处理认证头添加,代码如下:
// 配置HTTPS绑定,开启Basic传输认证 var binding = new BasicHttpsBinding(); binding.Security.Mode = BasicHttpsSecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; // 初始化服务地址,不需要额外加AddressHeader var endpointAddress = new EndpointAddress("https://dm-delta.metapack.com/dm/services/ConsignmentService"); var client = new ConsignmentServiceClient(binding, endpointAddress); // 配置认证凭据 client.ClientCredentials.UserName.UserName = "你的用户名"; client.ClientCredentials.UserName.Password = "你的密码"; // 后续直接调用客户端方法即可
方案2:手动添加HTTP请求头
如果有特殊场景需要自行构造认证头,可以通过OperationContextScope在请求上下文里加HTTP头,示例如下:
// 先初始化客户端,不需要带AddressHeader var client = new ConsignmentServiceClient(ConsignmentServiceClient.EndpointConfiguration.ConsignmentService, new EndpointAddress("https://dm-delta.metapack.com/dm/services/ConsignmentService")); using (var scope = new OperationContextScope(client.InnerChannel)) { // 构造认证信息 string credential = "UserName:Password"; string authHeaderValue = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credential)); // 添加到HTTP请求头 HttpRequestMessageProperty httpRequestProps = new HttpRequestMessageProperty(); httpRequestProps.Headers["Authorization"] = authHeaderValue; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProps; // 在using块内调用服务方法即可生效 var response = client.你要调用的服务方法(); }
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

