我昨天开始了一个POC项目连接到现有的WCF服务,我正在使用.Net Core 2.1 Web API应用程序和Swagger发布我的测试请求消息。我正在使用BasicHttpBinding和Transport for BasicHttpSecurityMode。
在发送测试请求消息时,我收到以下异常:
“HTTP请求未经授权使用客户端身份验证方案'Anonymous'。从服务器收到的身份验证标头是'Basic Realm'。”
然后,我使用.NET Framework 4.6.1创建了一个Microsoft Web API项目来调用WCF服务,并且我能够获得状态代码200 HTTP响应。
在我看来,这似乎是连接到WCF服务的.NET Core 2 Web API项目的问题。我做了一些研究,看起来这个设计架构肯定是可能的。
微软甚至开发了一个提供程序工具来完成这个,这里是关于其提供程序工具的MS文章的链接:https://docs.microsoft.com/en-us/dotnet/core/additional-tools/wcf-web-service-reference-guide
我甚至试图让我的.NET Core Web API控制器调用我在.NET 4.6.1类库项目中构建的处理程序类无济于事,我仍然得到“HTTP请求未经授权使用客户端身份验证方案'Basic' 。从服务器收到的身份验证标头是“Basic Realm”。“例外。
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IInsuranceService))
{
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
return result;
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IInsuranceService))
{
return new System.ServiceModel.EndpointAddress("https://myservicebaseURL\myservice.svc");
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
感谢大家的投入。我能够通过遵循此article中详述的步骤来解决我的问题。
请阅读下面的更新代码,从我的.NET Core 2 Web Api调用WCF服务:
public async Task<DataFetchServiceResponseUsingPatient> FetchEntity(String ID)
{
var userName = _authenticationSettings.Value.UserName;
var password = _authenticationSettings.Value.Password;
var url = _authenticationSettings.Value.Url;
var basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
ChannelFactory<IMyService> factory = null;
factory = new ChannelFactory<IMyService>(basicHttpBinding, new EndpointAddress(new Uri(url)));
factory.Credentials.UserName.UserName = userName;
factory.Credentials.UserName.Password = password;
var serviceProxy = factory.CreateChannel();
((ICommunicationObject)serviceProxy).Open();
var opContext = new OperationContext((IClientChannel)serviceProxy);
var prevOpContext = OperationContext.Current;
OperationContext.Current = opContext;
var result = await serviceProxy.MyWCFServiceMethod(ID);
//Cleanup Factory Objects
factory.Close();
((ICommunicationObject)serviceProxy).Close();
return result;
}