Search code examples
c#wcfwebhttpbinding

Defining 'app.config' for a WCF service using WebHttpBinding


I've got a WCF service that allows the uploading of files without using a MessageContract.

[OperationContract, WebInvoke(UriTemplate = "UploadFile?filename={filename}")]
bool UploadFile(string filename, Stream fileContents);

I'm allowed to use another parameter beside the Stream object because it's part of the UriTemplate. Since the service runs as a Managed Windows Service, I have to start the ServiceHost manually.

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();
}

With all of this, the service starts up and works just fine. However I wanted to move some of the above to the app.config file. To do this, I commented out the second line of OnStart and replaced the first line with FileServiceHost = new ServiceHost(typeof(FileService)). Then I added that info to the 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>

And suddenly the service can no longer start up. It throws this exception on FileServiceHost.Open of the OnStart method: "For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream."

There must be something wrong with the way I'm defining the service in app.config, because when I remove it from there, everything works fine. What am I doing wrong here?


Solution

  • Here's how I fixed the issue by adding webHttpBinding to the endpoint behavior.

    Added behaviorConfiguration="TestBehavior" to <endpoint address="" binding="webHttpBinding" contract="IFile"/>, and then defined TestBehavior as follows:

    <endpointBehaviors>
        <behavior name="TestBehavior">
          <webHttp />
        </behavior>
    </endpointBehaviors>