views:

84

answers:

1

Hey, I've never used HTTP Handlers before, and I've got one working, but I'm not sure if I'm actually using it properly. I have generated a string which will be saved as a CSV file. When the user clicks a button, I want the download dialog box to open so that the user can save the file. What I have works, but I keep reading about modifying the web.config file and I haven't had to do that.

My Handler:

private string _data;
private string _title = "temp";


public void AddData(string data)
{
    _data = data;
}



public bool IsReusable
{
    get { return false; }
}

public void ProcessRequest(HttpContext context)
{

    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("content-disposition","filename=" + _title + ".csv");
    context.Response.Write(_data);
    context.Response.Flush();
    context.Response.Close();

}

And this is from the page that allows the user to download: (on button click)

string dataToConvert = "MYCSVDATA....";

csvHandler handler = new csvHandler();
handler.AddData(dataToConvert);

handler.ProcessRequest(this.Context);

This works fine, but no examples I've seen ever instantiate the handler and always seem to modify the web.config. Am I doing something wrong?

Thanks

+4  A: 

It seems to me that it's not really using the fact that it's a handler at all. What is the benefit in making a separate class for this implementing an interface you don't really use, rather than putting the code within your existing page class? You're only doing things to the response - so why not just do that within the page?

The typical approach of modifying web.config is because you want the handler to actually handle the request - whereas in your case the page is receiving the request, and just asking an object which happens to implement the handler interface to dump the data into the response.

In particular, would this handler be usable at all as a standalone handler for a normal response? It feels like it's only going to do anything useful when you've called AddData on it... if you did register it in web.config, it would just respond with an empty csv file (or possibly an exception), right? If that's the case, I really don't think it should implement the IHttpHandler in the first place - it will mislead other developers who look at it later.

Jon Skeet
Thank you for the reply. I originally had it in the code page, but I read a forum post where someone said that it would be more efficient to use a handler to allow users to download. I guess their scenario must've been different (i.e. doing more than just using the response property).
SSL