从RESTful WCF服务返回图像

Returning an image from a RESTful WCF service

本文关键字:返回 图像 服务 WCF RESTful      更新时间:2023-09-26

我有一个非常简单的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();
}

在我的全局。我有:

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可以将其扔到屏幕上?

目前还好。现在,我如何把字节数组转换成图像呢?

既然你已经用javascript标记了你的问题,我假设这是你用来消费服务的,你想在浏览器中显示图像。如果是这种情况,您可以查看Data URI方案,该方案允许您在给定从服务获得的字节的情况下显示图像。

下面是一个示例,您可以使用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函数来自于这个插件

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

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

asp.net Web API下载二进制图像

如果你实现一个自定义的HTTP处理程序,你会更开心。api是用于结构化数据的,而图像不是结构化数据——它们是二进制的。它们在HTTP中有自己的位置,我认为将它们与API分离是一个好主意。