从RESTful WCF服务返回映像

时间:2011-12-01 10:59:33

标签: c# javascript wcf rest

我有这个非常简单的DTO:

[DataContract]
public class DTO
{
    [DataMember]
    public byte[] Image {get; set; }
}

这个非常简单的服务:

[ServiceContract]
public interface IFooService
{
    [WebGet(
        UriTemplate = "", 
        RequestFormat = WebMessageFormat.Json, 
        ResponseFormat = WebMessageFormat.Json)]
    List<DTO> GetDTOs();
}

在我的global.asax中,我有:

RouteTable.Routes.Add(new ServiceRoute("foo", 
    new WebServiceHostFactory(), typeof(FooService)));

现在,当我从浏览器调用它时,我得到一个JSON格式的字节数组。目前很好。现在,如何将该字节数组转换为图像?

或者,有没有更好的方法来解决这个问题?我尝试将byte[]更改为Stream,但是当我从Firefox调用该服务时,尽管HTTP状态代码为200,但响应为空。我正在使用Firebug和Fiddler。

我不认为它是相关的,但是因为太多信息从来没有伤害任何不是机器人的人,所以这是web.config:

<?xml version="1.0"?>
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
            <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </modules>
    </system.webServer>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

最终,我想问题是:如何从WCF RESTful服务返回位图,以便在浏览器中运行的JavaScript可以将其丢弃在屏幕上?

2 个答案:

答案 0 :(得分:4)

  

到目前为止很好。现在,如何将该字节数组转换为图像?

由于您使用javascript标记了您的问题,我认为这是您使用服务所需的内容,并且您希望在浏览器中显示该图像。如果是这种情况,您可以查看Data URI scheme,这样您就可以根据从服务中获得的字节来显示图像。

以下是如何使用jQuery使用此类服务​​并显示图像的示例:

$(function () {
    $.getJSON('/foo/', function (dtos) {
        $.each(dtos, function (index, dto) {
            var str = String.fromCharCode.apply(String, dto.Image);
            $('<img/>', {
                alt: '',
                src: 'data:image/png;base64,' + $.base64.encode(str)
            }).appendTo('body');
        });
    });
});

$.base64.encode功能来自this plugin

答案 1 :(得分:0)

使用WCF执行此操作的问题在于Web服务框架(特别是WCF)对结果响应做出了很多假设。当您从服务器请求图像时,HTTP响应内容类型通常与API请求的类型不同。

这就是为什么我认为不应该使用WCF实现这样的工作。我刚回答了一个类似的问题,但是使用WebAPI而不是WCF:

ASP .Net Web API downloading images as binary

如果您只是实施自定义HTTP handler,您会更开心。 API用于结构化数据,而图像不是结构化数据 - 它们是二进制的。他们在HTTP中有自己的位置,我认为将它们与API脱钩是一个好主意。