使用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,BadRequest,因为服务期望Request头中没有它的“授权”。
答案 0 :(得分:0)
我们可以使用WebOperationContext类来更改和添加HTTP标头,请参考以下代码段。
IService service = factory.CreateChannel();
using (OperationContextScope scope = new OperationContextScope((IContextChannel)service))
{
WebOperationContext.Current.OutgoingRequest.ContentType = "application/json; charset=utf-8";
WebOperationContext.Current.OutgoingRequest.Headers.Add("Authorization", "bearer xxxxxxxx");
service.GetData();
}
结果。
有关详细信息,
https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.web.weboperationcontext?redirectedfrom=MSDN&view=netframework-4.8
随时让我知道是否有什么可以帮助您的。