我创建了一个名为MiniCalc的基本计算器服务,它只有两个操作。添加和Mul,并将其托管在控制台应用程序中。
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service),
new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),
new BasicHttpBinding(),
"Service");
host.Open();
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
}
然后我创建了一个控制台应用程序来使用该服务并通过创建代理类手动创建代理,然后创建一个ChannelFactory来调用该服务。
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService/Service");
IService proxy = ChannelFactory<IService>.CreateChannel(new BasicHttpBinding(),ep);
我能够正确调用服务合约并按预期检索结果。
现在我想使用Add Service Reference
创建代理。
在“添加服务引用”窗口中单击“执行”时出现以下错误
There was an error downloading 'http://localhost:8091/MiniCalcService/Service'.
The request failed with HTTP status 400: Bad Request.
Metadata contains a reference that cannot be resolved: 'http://localhost:8091/MiniCalcService/Service'.
Content Type application/soap+xml; charset=utf-8 was not supported by service http://localhost:8091/MiniCalcService/Service. The client and service bindings may be mismatched.
The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'..
If the service is defined in the current solution, try building the solution and adding the service reference again.
我错过了什么或做错了什么?
答案 0 :(得分:3)
在ServiceHost中启用元数据交换行为。
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service),
new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),
new BasicHttpBinding(),
"Service");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
}
答案 1 :(得分:1)
由于您没有.svc,我认为您必须在服务中使用.config:
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
<serviceActivations>
<add relativeAddress="Service.svc" service="MiniCalcService.Service" />
</serviceActivations>
</serviceHostingEnvironment>
之后,您需要一个允许服务元数据的选项:
<serviceMetadata httpGetEnabled="true" />
这有点复杂所以我建议你在一个新的解决方案中创建一个新的WCF服务然后你可以看到这个配置的样子。所以你只需要进行一些复制/粘贴配置。
在此之后: