首页 > 解决方案 > 如何为 WCF SOAP 服务传递标头

问题描述

我正在尝试通过 C# 控制台应用程序使用 WCF SOAP 服务。

我在上下文中有 2 个服务,一个用于通过传递用户名和密码来获取身份验证令牌,第二个用于获取所需的数据,该服务期望之前生成的令牌作为名称为“令牌”的标头传递

当我使用 SOAP UI 调用服务时,这工作正常,我们可以选择发送 Header 名称和值

但我无法找到以编程方式执行相同操作的方法 下面是我尝试过的示例代码

SecurityService.IInteropSecurityService authenticationClient = new SecurityService.InteropSecurityServiceClient();

string token = client.GetAuthenticationToken("cfadmin", "305f2a0ebb646a2ab32689d5b9c01532");


EntityService.InteropEntityServiceClient entityClient = new EntityService.InteropEntityServiceClient();

 using (new OperationContextScope(entityClient.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers["Token"] = token;

                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

            }
entityClient.GetEntity("Test name");

当我尝试这个时,它会得到我

mscorlib.dll 中出现“System.ServiceModel.Security.SecurityAccessDeniedException”类型的未处理异常附加信息:访问被拒绝。

标签: c#wcf

解决方案


OperationContxtScope 的作用域只在Using 语句中有效,即带有特定soap 头的服务请求在Using 语句中有效。另一个调用在 Using 语句之外恢复,没有特定的标头。
如果我们想为每个请求永久添加消息头,我们可以使用 IClientMessageInspector 接口。
https://putridparrot.com/blog/adding-data-to-wcf-message-headers-client-side
请参考我之前的回复。
在 WCF 中添加外发邮件标头无法在传入邮件标头中检索
如果有什么我可以提供帮助的,请随时告诉我。


推荐阅读