Search code examples
c#asp.nethttphandlerfile-type

One .ashx generic handler for all file types?


I've gone through the basic MSDN information and a few tutorials. From what I've learned so far, I have been able to make two .ashx handlers, that I call ImageHandler.ashx and PDFHandler.ashx. They do what you would expect: return images or PDFs, respectively. For both of these handlers, in the ProcessRequest method, I'm setting context.Response.ContentType to "image/jpeg" and "application/pdf", respectively, then writing the result with context.Response.BinaryWrite(bytes) So far this works just fine.

However, I want to allow a user to have the ability to download any file, regardless of type. Do I really need to create a different Handler for every file type?

Can I just have one .ashx file and then have a switch statement based on the file type (which I would get via substring of the filename)? Even if I do that, what about file types that aren't standard, like say .xyz files? What do I set the content.Response.ContentType to in that case?


Solution

  • No, you do not need multiple handlers, especially if the fundamental operation is the same. Yes, you can use any kind of logic you want to decide what to set the response content-type to. For something you don't know, use application/octet-stream. You should also consider setting the "content-disposition" header, which gives you a chance to suggest whether it should be shown "inline" (i.e. in the browser), or prompted as a download - and what the logical filename is (rather than some ashx page).