0

I'm trying to save a Http Reponse into a Session variable, but I get this error

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

private System.Web.HttpResponse _response;

Function1()
{
    Response.ContentType = "application/vnd.ms-excel";
    string attachment = "attachment; filename=Prac_Query_Report.xls";
    //Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    //Response.ContentType = "application/ms-excel";
    StringWriter stw = new StringWriter();
    HtmlTextWriter htextw = new HtmlTextWriter(stw);
    //ctl.RenderControl(htextw);
    _response = (System.Web.HttpResponse)Session["hi"];
    _response.Write(stw.ToString());
    FileInfo fi = new FileInfo(Server.MapPath("~/Stylesheets/Styles1.css"));
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    StreamReader sr = fi.OpenText();
    while (sr.Peek() >= 0)
    {
        sb.Append(sr.ReadLine());
    }
    sr.Close();
    Response.Write("<html><head><style type='text/css'>" + sb.ToString() + "</style>" + stw.ToString() + "</head></html>");
    stw = null;
    htextw = null;
}

Function2()
{
    Response.Write(footerBuilder.ToString());
    Session["hi"] = Response;
}
Marc
  • 3,905
  • 4
  • 21
  • 37
jan86
  • 107
  • 2
  • 15
  • Your class needs to be marked as `[Serializable()]` to be serialised. You cannt save a `Response` object because it is not serializeable – Liam Dec 20 '16 at 14:21
  • I suggest you save the bits of the response into some other object (maybe of your own creation) which is serializable. Or maybe store it somewhere else like a database. Incidentally I'm fascinated to know what the use is that requires this. Smells like a workaround or an X Y problem. – ADyson Dec 20 '16 at 14:53
  • What are you trying to achieve here? The `HttpResponse` represents the current act of responding to a web request. It's meaningless outside of that context, so if it was serialisable it wouldn't do anything useful. What would it mean to write a string to a browser half an hour after it had disconnected, for example? What's the end-goal here? – Jon Hanna Dec 20 '16 at 15:33

0 Answers0