javascript 从 RESTful WCF 服务返回图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8340247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:06:29  来源:igfitidea点击:

Returning an image from a RESTful WCF service

c#javascriptwcfrest

提问by Amy

I have this very simple DTO:

我有这个非常简单的 DTO:

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

And this very simple service:

这个非常简单的服务:

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

In my global.asax, I have:

在我的 global.asax 中,我有:

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

Now, when I call this from my browser, I am getting an array of bytes in JSON format. Good so far. Now, how do I turn that array of bytes into an image?

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

Or, is there a better way of going about this? I tried changing byte[]to Stream, but then when I call the service from Firefox, the response is empty despite an HTTP status code of 200. I am using Firebug and Fiddler.

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

I don't think it's relevant, but since too much information never hurt anybody who wasn't a robot, here's the web.config:

我认为这无关紧要,但由于过多的信息永远不会伤害非机器人的任何人,这里是 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>

Ultimately, I guess the question is: how do you return a bitmap from a WCF RESTful service so JavaScript running in the browser can throw it up on the screen?

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

回答by Darin Dimitrov

Good so far. Now, how do I turn that array of bytes into an image?

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

Since you have tagged your question with javascript I assume that this is what you use to consume the service and you want to display the image in the browser. If this is the case you may take a look at the Data URI schemewhich would allow you to show the image given the bytes you get from the service.

由于您已使用 javascript 标记了您的问题,因此我假设这是您用来使用服务的内容,并且您希望在浏览器中显示图像。如果是这种情况,您可以查看数据 URI 方案,它允许您根据从服务获得的字节显示图像。

Here's an example how you could consume such service using jQuery and show the image:

以下是如何使用 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');
        });
    });
});

The $.base64.encodefunction comes from this plugin.

$.base64.encode功能来自这个插件

回答by Slavo

The problem with using WCF to do this is that web service frameworks (and WCF in particular), make a lot of assumptions on the resulting response. When you request an image from a server, the HTTP response content type is usually different than that of an API request.

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

This is why I don't think such a job should be implemented using WCF. I just answered a similar question asking the same, but with WebAPI rather than WCF:

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

ASP .Net Web API downloading images as binary

ASP .Net Web API 将图像下载为二进制文件

You'd be much happier if you just implement a custom HTTP handler. APIs are for structured data, and images are not structured data - they are binary. They have their own place in HTTP and I think decoupling them from the API is a good idea.

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