【问题标题】:C# WCF JSON WebService to return mime-type image/pngC# WCF JSON WebService 返回 mime 类型的图像/png
【发布时间】:2013-09-13 21:18:33
【问题描述】:

我正在使用 JSON 格式运行 WCF Web 服务,如下所示。我的问题是响应格式是 Alowas 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);

【问题讨论】:

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


    【解决方案1】:
    1. 使用WebOperationContext.Current

    2. 返回Stream

    你的方法应该是这样的

    [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;
    }
    

    【讨论】:

    • 你将如何阅读另一边的图像?使用 BeginRead 逐块?以下代码抛出异常“参数无效”Stream data = client.GetImage(); canvas.Image = (Bitmap)Bitmap.FromStream(data);
    • 类似于从网站读取图像。在浏览器中输入其 url 并查看结果。
    • 即使我将传输模式启用为 Streamed 或 StreamedResponse,在客户端和服务器上我都会在读取图像时遇到异常。我仍在试图弄清楚如何读取流。稍后将发布代码。
    • 我尝试关注this article,但即使我设置了内容长度,客户端也会看到内容长度:0
    • 我在上面更改了您的代码。您必须将内存流的位置重置为 0。
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2010-10-27
    • 2012-11-29
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多