C#WCF JSON WebService返回mime-type image / png

时间:2013-09-10 08:41:08

标签: c# json wcf web-services wcf-rest

我正在使用JSON格式运行WCF Web服务,如下所示。我的问题是响应格式是json或XML,但对于GetImage,我想将图像作为mime-type image-png返回。知道如何在WCF中执行此操作吗?提前谢谢。

[ServiceContract]
public interface IEditor
{
    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/GetImage", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    byte[] GetImage();

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetBounds", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void GetBounds(out Rectangle bounds, out Point[] viewport);

1 个答案:

答案 0 :(得分:2)

  1. 使用WebOperationContext.Current

  2. 返回Stream

  3. 你的方法应该是这样的

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/GetImage", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    public Stream GetImage()
    {
        var m = new MemoryStream();
        //Fill m
    
        // very important!!! otherwise the client will receive content-length:0
        m.Position = 0;
    
        WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
        WebOperationContext.Current.OutgoingResponse.ContentLength = m.Length;
        return m;
    }