我需要使用ConfigurationChannelFactory.CreateChannel时请求头添加到WCF请求。
使用OperationContextScope我已经试过了。
我具有被如下所示的函数:
public O Execute<O>(Func<T, O> action, string configFilePath, string endpoint, StringDictionary headers)
{
bool closed = false;
T channel = default(T);
O output = default(O);
try
{
channel = this.GetChannel(configFilePath, endpoint);
if (headers != null && headers.Count > 0)
{
(channel as IClientChannel).Open();
using (new OperationContextScope(channel as IClientChannel))
{
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
foreach (DictionaryEntry header in headers)
{
requestMessage.Headers[header.Key.ToString()] = header.Value.ToString();
}
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
output = action(channel);
}
(channel as IClientChannel).Close();
}
else
{
(channel as IClientChannel).Open();
output = action(channel);
(channel as IClientChannel).Close();
}
closed = true;
}
finally
{
if (!closed && channel != null)
{
(channel as IClientChannel).Abort();
}
}
return output;
}
private T GetChannel(string configFilePath, string endpoint)
{
//Get the ChannelFactoryObject
ConfigurationChannelFactory<T> wcfClientFactory = null;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
wcfClientFactory = new ConfigurationChannelFactory<T>(endpoint, ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None), null);
return wcfClientFactory.CreateChannel();
}
配置文件条目:
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />;clientCredentialType="Windows" negotiateServiceCredential="true" />
</security>
上述功能是从另一个cs文件调用,如以下所示,通过Func<T,O>
作为参数:
Execute<MyService.InformationResponse[]>=>IMyService.GetInformation(Request), ConfigPath, myServiceEndPoint, headers);
我得到400错误请求的服务的请求头,它是不是能找到期待“授权”。