C# WCF JSON WebService 返回 mime 类型 image/png

标签 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. 使用WebOperationContext.Current

  2. 返回

你的方法应该是这样的

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

关于C# WCF JSON WebService 返回 mime 类型 image/png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714256/

相关文章:

python - 从 JSON 中提取数据并使用 python 进行迭代

java - Gson 无法反序列化 List<Serialized>

wcf - DataContract 属性-WCF

c# - 如何在 ASP.NET Core 1.1 中对使用 HttpContext 的 MVC Controller 进行单元测试

c# - 从 Azure 辅助角色建立 WSManConnection

java - 将 JSON 转换为 Getter/Setter 语句

c# - Wcf 服务异常良好实践

c# - WCF 私有(private)内存使用增加查询

c# - 在 Visual Studio 中格式化文档以插入大括号?

C# 创建 Excel(完成)然后显示/打开它?帮助