Amy*_*Amy 5 javascript c# rest wcf
我有这个非常简单的DTO:
[DataContract]
public class DTO
{
[DataMember]
public byte[] Image {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这个非常简单的服务:
[ServiceContract]
public interface IFooService
{
[WebGet(
UriTemplate = "",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<DTO> GetDTOs();
}
Run Code Online (Sandbox Code Playgroud)
在我的global.asax中,我有:
RouteTable.Routes.Add(new ServiceRoute("foo",
new WebServiceHostFactory(), typeof(FooService)));
Run Code Online (Sandbox Code Playgroud)
现在,当我从浏览器调用它时,我得到一个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>
Run Code Online (Sandbox Code Playgroud)
最后,我想问题是:如何从WCF RESTful服务返回位图,以便在浏览器中运行的JavaScript可以在屏幕上抛出它?
目前很好。现在,如何将该字节数组转换为图像?
由于您已使用 javascript 标记了您的问题,我假设您使用的是该服务来使用该服务,并且您希望在浏览器中显示图像。如果是这种情况,您可以查看数据 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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
该$.base64.encode功能来自于这个插件。
| 归档时间: |
|
| 查看次数: |
17956 次 |
| 最近记录: |