Search code examples
c#asp.nethttpcontextashxgeneric-handler

Pass a dataset to Generic handler (ashx)


How can I pass a dataset to a generic handler? I don't want to use session or viewstate to do that.

I'm trying to return an excel file converted from the input dataset as the response.

I'm already showing the dataset content as a report in one grid filtered with some criteria set by user. Since the query is expensive, I don't want to execute the same in the handler too.

It would be even better if I could pass the dataset by reference to the handler?


Solution

  • I couldn't find any way to pass dataset to ashx other than creating an object of the handled class and assign to it. Then I called the object's ProcessRequest method. It worked fine and the build was succeeded. But when I tried to publish the website, the code gave error that the classname could not be found. The code is just like given below.

    //this is working fine in VS (build succeeded and ProcessRequest returned the file!) 
    //but didn't compile only on publishing
    MyHandler handlerObj = new myHandler();
    handlerObj.DataSource = myDataset;
    handlerobj.ProcessRequest(Context);
    

    I solved the problem by replacing the generic handler with a normal c# class which has a method accepting the context and dataset. Then I called the method in the class, where I wrote my file stream into the Context.Response and it worked just fine. The class did just the same as the handler and no need to inherit from IHttpContext

    public void ProcessDownload(HttpContext context, DataSet DataSource)
    {
        context.Response.Clear();
        context.Response.ContentType = "application/vnd.ms-excel";
        MemoryStream file = getExcelMemStream(DataSource);
        context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "myFile.xls"));
        context.Response.BinaryWrite(file.GetBuffer());
        context.Response.End();
    }