Search code examples
c#wcfstreamdatacontract

WCF service streaming images


I'd like to make WCF service which can put image into stream.

I have next in config:

<service name="Images" behaviorConfiguration="ImagesBehavior">
    <endpoint address="http://localhost:5523/Images.svc"
       binding="basicHttpBinding" contract="Images" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:5523/Images" />
      </baseAddresses>
    </host>
</service>

<behavior name="ImagesBehavior">
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceMetadata httpGetEnabled="true" />
</behavior>

And code:

[OperationContract]
[WebGet(UriTemplate = "GetImage/{imageID}",
    BodyStyle = WebMessageBodyStyle.Bare)]
public Stream GetImage(string imageID)
{
    try
    {

        if (WebOperationContext.Current != null)
            WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

        var ms = new MemoryStream(myImage);
        return ms;
    }
    catch (Exception e)
    {
if (WebOperationContext.Current != null)
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        Console.WriteLine("GetImage ERROR:" + e.Message + "\r\n" + e.StackTrace);
        byte[] errorBytes = Encoding.UTF8.GetBytes("ERROR");
        return new MemoryStream(errorBytes);
    }
}

But when I'm trying this via browser like

http://localhost:5523/Images.svc/GetImage/imagecodeblabla

I've got

400 Bad Request

And when

http://localhost:5523/Images/GetImage/imagecodeblabla

405 Method Not Allowed

What's wrong?


Solution

  • Is your service SOAP or REST? It appears that you're using REST syntax (WebGetAttribute) but your binding is BasicHttpBinding (SOAP).

    Try using WebHttpBinding instead and see how that goes!