Friday, October 12, 2007

CodeBehind handlers in ASP.NET

I was creating an HTTP handler for an ASP.NET project today for returning a CSV report to a customer. And naturally I wanted this to CodeBehind style as everything else. This turned out to be a small gotcha, since it is not supported out of the bag with VS.NET 2005. So for further reference here is what to do.

1. Create the handler as usual - for instance MyHandler.ashx.

2. Create a new code file for the handler - MyHandler.cs - make sure this goes in the App_Code directory otherwise it will not be compiled properly and you will get a "Could not find class: MyHandler" error.

3. Copy all code from MyHandler.ashx to the new code file, replacing all code there.

4. Add CodeBehind="~/App_Code/MyHandler.cs" to the WebHandler directive at the top of the MyHandler.ashx file.

Done deal. Why the code file has to go into the App_Code directory and cannot stay alongside the ashx-file as other handlers do is an open question. I am betting that there is some odd web.config fix for this.

No comments: