WCF返回MemoryStream返回空白并且状态为202

时间:2020-03-05 10:54:36

标签: c# wcf

我的WCF服务正在代理另一个Web服务。每当我修改响应并返回内存流时,客户端都会获得202-Accepted。

public Stream MyMethod()
    {
        ...
        ...

        HttpWebResponse httpGetResponse = (HttpWebResponse)httpGetRequest.GetResponse();
        var result = httpGetResponse.GetResponseStream();

        //if I return "result" here, I get a 200 and Messagebody contains the contents of the stream
        //return result;

        //modifying content body
        var txtresult = new StreamReader(result, Encoding.UTF8).ReadToEnd();
        txtresult = txtresult.Replace("old text", "new text");

        var stream = new MemoryStream();
        stream.Write(Encoding.UTF8.GetBytes(txtresult), 0, Encoding.UTF8.GetBytes(txtresult).Length);
        //same as:- new MemoryStream(Encoding.UTF8.GetBytes(txtresult));

        stream.Position = 0L;
        //stream.Flush();

        //returns 202 - Accepted. Content body is empty
        return stream;
    }

基本上,我只需要修改流的内容,然后再将其填充到客户端应用程序即可。我已验证编码正确。除此之外,我不确定自己在做什么错。请你帮忙

此外,接口定义如下:

    [WebInvoke(Method = "GET",
             BodyStyle = WebMessageBodyStyle.Bare,
             UriTemplate = "teststream")]
    Stream MyMethod();

2 个答案:

答案 0 :(得分:0)

在返回响应之前,您需要设置OutgoingResponse.ContentType并添加Content-Disposition标头,如下所示:

public Stream MyMethod()
{
    ...

    var stream = new MemoryStream();
    stream.Write(Encoding.UTF8.GetBytes(txtresult), 0, Encoding.UTF8.GetBytes(txtresult).Length);

    stream.Position = 0L;

    WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=result.txt");

    return stream;
}

答案 1 :(得分:0)

我终于设法解决了。由于我的服务是代理,因此我将接收到的标头传递给客户端,而没有对其进行任何修改。在返回流之前删除Content Encoding标头对我有用

   public Stream MyMethod()
{
    ...

    HttpWebResponse httpGetResponse = (HttpWebResponse)httpGetRequest.GetResponse();
    var result = httpGetResponse.GetResponseStream();

    var txtresult = new StreamReader(result, Encoding.UTF8).ReadToEnd();
    txtresult = txtresult.Replace("old text", "new text");

    var stream = new MemoryStream();
    stream.Write(Encoding.UTF8.GetBytes(txtresult), 0, Encoding.UTF8.GetBytes(txtresult).Length);

    stream.Position = 0L;
//added this line 
WebOperationContext.Current.OutgoingResponse.Headers.Remove(HttpRequestHeader.ContentEncoding);


    //now returns actual content to client
    return stream;
}