c# Excel response with httphandler

An example of excel output used by HttpHandler

public class IExcelHandler : IHttpHandler
    {
 
        #region IHttpHandler Members
 
        public bool IsReusable
        {
            get { return false; }
        }
 
        public void ProcessRequest(HttpContext context)
        {
            // set Content type for Excel
            context.Response.ContentType = "application/vnd.ms-excel";
            // for download and give a file name
            context.Response.AppendHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            context.Response.Charset = "";
 
            //Write here your content
            // context.Response.Write(data);
 
            context.Response.End();
        }
 
        #endregion
    }
...
Advertisements

HttpHandler with Session State

If you are developing httphandler in asp.net realized that httphandlers can not use session as default.If you want to access session object do it as below.

Add  “System.Web.SessionState” namespace to your handler code.

There are two interface . one of them  must be inherited by your httphandler object:

IRequiresSessionState Interface

Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

IReadOnlySessionState Interface
Specifies that the target HTTP handler requires only read access to session-state values. This is a marker interface and has no methods.
 
 Example :
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
 
namespace PostmanExamples
{
 
    // IRequireSessionState if you want write access
    public class MyHttpHandlerWithSessionState
        : IHttpHandler, IReadOnlySessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            string s = context.Session["SomeSessionVariable"];
        }
 
        public bools IsReusable { get { return true; } }
    }
}

HttpHandler content-type as xml

        XmlNode xml = e.Xml;

        this.Response.Clear();

        string strXml = xml.OuterXml;
        this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
        this.Response.AddHeader("Content-Length", strXml.Length.ToString());
        this.Response.ContentType = "application/xml";
        this.Response.Write(strXml);

        this.Response.End();