我有一个 WCF 服务,允许在不使用 MessageContract 的情况下上传文件。
[OperationContract, WebInvoke(UriTemplate = "UploadFile?filename={filename}")]
bool UploadFile(string filename, Stream fileContents);
我可以使用 Stream 对象旁边的另一个参数,因为它是 UriTemplate 的一部分。由于该服务作为托管 Windows 服务运行,因此我必须手动启动 ServiceHost。
protected override void OnStart(string[] args)
{
FileServiceHost = new ServiceHost(typeof(FileService), new Uri("http://" + Environment.MachineName + ":8000/FileService"));
FileServiceHost.AddServiceEndpoint(typeof(IFile), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
FileServiceHost.Open();
}
完成所有这些后,服务即可启动并正常工作。但是我想将上面的一些内容移动到 app.config 文件中。为此,我注释掉了 OnStart 的第二行,并将第一行替换为 FileServiceHost = new ServiceHost(typeof(FileService))。然后我将该信息添加到 app.config...
<system.serviceModel>
<services>
<service name="Test.Server.FileService" behaviorConfiguration="DefaultBehavior">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8000/FileService"/>
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="IFile"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
服务突然无法启动。它在 OnStart
方法的 FileServiceHost.Open
上引发此异常:“为了使 UploadFile 操作中的请求成为流,该操作必须具有类型为 Stream 的单个参数。”
我在 app.config 中定义服务的方式一定有问题,因为当我从那里删除它时,一切正常。我在这里做错了什么?
最佳答案
以下是我通过添加 webHttpBinding
解决问题的方法到端点行为。
已添加behaviorConfiguration="TestBehavior"
至<endpoint address="" binding="webHttpBinding" contract="IFile"/>
,然后定义TestBehavior
如下:
<endpointBehaviors>
<behavior name="TestBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
关于c# - 使用 WebHttpBinding 为 WCF 服务定义 'app.config',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314241/