如何获取/使用HttpContext.Response.OutputStream?

时间:2018-08-18 14:33:23

标签: c# infopath

任何帮助都将得到感谢!

我们有一些基于浏览器的InfoPath(经管理员批准)表格,其中包含Code Behind。
我有一些商务任务,当用户键入一些增值税ID时,需要检查增值税ID是否有效并返回信息作为消息框。

好的,我已经对VIES使用了一些Web服务调用。

string dicValue = FormMethods.GetIpFieldValue(currentForm, formFields.PoDicIPField);
string countryCode = dicValue.Substring(0, 2);
string vatId = dicValue.Substring(2, (dicValue.Length - 2));

this.DataConnections["WebServices-Query-SOAP-CheckVat"].Execute();
bool isVatValid = FormMethods.CheckVAT(this.DataSources);
string notification = "This VAT is valid.";
if (isVatValid != true)
{
    notification = "This VAT is not valid!";
}

然后,我尝试将警报发送回页面。

HttpContext currentContext = System.Web.HttpContext.Current;
currentContext.Response.Write("<script type=\"text/javascript\">alert('" + notification + "'); </script>");


OK alert
当用户在警报中单击“确定”(失去页面内容)后,我的问题开始了。
Page look likes this
因为InfoPath表单在加载时会加载“ FormServer.aspx”页面的上下文。
当用户单击按钮时,InfoPath表单将获得“ PostBack.FormServer.aspx”页面的上下文。

所以我需要:
1)存储来自负载的原始响应OutputStream
2)发送警报
3)重写currentContext.Response并通过来自负载的原始响应进行响应

但是,当我尝试将currentContext.Response.OutputStream保存在任何对象(例如byte [])中时,出现以下异常:“流不可读”。

        byte[] currentContextResponseOutputStreamBytes = null;
        using(Stream stream = currentContext.Response.OutputStream)
        using (MemoryStream memoryStream = new MemoryStream())
        {
            stream.Dispose();
            int count = 0;
            do
            {
                byte[] buffer = new byte[1024];
                count = stream.Read(buffer, 0, 1024);
                memoryStream.Write(buffer, 0, count);
            }
            while (stream.CanRead && count > 0);
            currentContextResponseOutputStreamBytes = memoryStream.ToArray();
        }

您能帮我完成这个任务吗?
谢谢

1 个答案:

答案 0 :(得分:0)

这里的问题似乎微不足道。您首先在流对象上调用dispose,然后尝试读取它。这是行不通的,因为要处理“破坏”流,因此没有更多可读取的内容了。这就是为什么您会得到例外。

要解决此问题,只需删除dispose调用即可。它应该在结尾而不是开头执行!此外,您根本不需要它,因为dispose将在using块的结尾自动执行。