[英]Returning an image from a RESTful WCF service
我有這個非常簡單的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可以在屏幕上拋出它?
目前很好。 現在,如何將該字節數組轉換為圖像?
由於您已使用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');
});
});
});
$.base64.encode
函數來自此插件 。
使用WCF執行此操作的問題在於Web服務框架(特別是WCF)對結果響應做出了很多假設。 從服務器請求映像時,HTTP響應內容類型通常與API請求的類型不同。
這就是為什么我認為不應該使用WCF實現這樣的工作。 我剛剛回答了一個類似的問題,但是使用WebAPI而不是WCF:
如果你只是實現一個自定義HTTP處理程序,你會更高興。 API用於結構化數據,而圖像不是結構化數據 - 它們是二進制的。 他們在HTTP中有自己的位置,我認為將它們與API分離是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.