WCF 服务流图像

WCF service streaming images

我想制作可以将图像放入流中的 WCF 服务。

我在配置中有下一个:

<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>

和代码:

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

但是当我通过浏览器尝试这个时

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

我有

400 Bad Request

而当

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

405 Method Not Allowed

怎么了?

您的服务是 SOAP 还是 REST?看来您使用的是 REST 语法 (WebGetAttribute),但您的绑定是 BasicHttpBinding (SOAP)。

尝试使用 WebHttpBinding,看看效果如何!