响应是不是在上下文中可用​​?如何解决呢? [英] Response is not available in context? How to solve it?

查看:176
本文介绍了响应是不是在上下文中可用​​?如何解决呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保存的PDF文件流。我想保存流响应流。但它总是抛出错误:响应不CONTEX用

I save a pdf file to stream. I want to save the stream to Response stream. But it always throw error:Response is not available in contex.

下面是代码:

using System;
using System.Threading;
using System.IO;

using Spire.Pdf;

namespace SingleThreadTest
{

    public partial class Test : System.Web.UI.Page
    {
        //[STAThread]
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        [STAThread]
        protected void Button1_Click(object sender, EventArgs e)
        {
            ////new a thread
            ThreadStart threadStart = HTMLToPDF;
            Thread thread = new Thread(threadStart);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        void HTMLToPDF()
        {
            PdfDocument doc = new PdfDocument();

            String url = "http://www.e-iceblue.com/";
            doc.LoadFromHTML(url, false, true, true);

            Response.ClearContent();
            Response.ClearHeaders();
            Response.BufferOutput = true;
            Response.ContentType = "application/pdf";

            using (MemoryStream pdfStream = new MemoryStream())
            {
                doc.SaveToStream(pdfStream);
                using (MemoryStream ms = new MemoryStream())
                {
                    //ms.WriteTo(Response.OutputStream);
                    Response.OutputStream.Write(pdfStream.ToArray(), 0, pdfStream.ToArray().Length);
                }
            }

            doc.SaveToHttpResponse("Test.pdf", Response, HttpReadType.Save);
            doc.Close();
        }
    }
}



我要送客户端的附件。如何acheive呢??(上面的代码我使用Spire.PDF的第三部分)。

I want to sent client an attachment. How to acheive it??(The above code i use the third component of Spire.PDF).

先谢谢了。

推荐答案

您开始新的线程来处理请求,但你原来的线程会继续执行并成功终止请求之前,您新的线程甚至已经开始做一些与响应。你必须等待在原来的线程新的线程完成(你可以创造性地使用异步页面不会阻止原来的线程的 http://msdn.microsoft.com/en-us/magazine/cc163725.aspx )。

You are starting new thread to process request, but your original thread likely continues execution and successfully terminates request before your new thread even gets to doing something with the response. You have to wait for completion of the new thread in the original thread (you may be able to creatively use asynchronous pages to not block original thread http://msdn.microsoft.com/en-us/magazine/cc163725.aspx).

这篇关于响应是不是在上下文中可用​​?如何解决呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆