Serving files from App_Data #1 - the naive approach.

by matt 5. October 2006 08:52

Don't worry, I've not gone crazy.

Asp.net 2 doesn't let you serve files from the App_Data folder, and for good reason - security. It's a folder your web app has write access to (a standard place on all installations without having to get your ISP involved - halellujah!) so in goes your databases and various other data files. You don't want anyone to be able to just download these, right? Right. Well, most of the time, anyway.

If you're dealing with a site that has mostly user-generated content, you're going to have to write a lot of data. The place of least friction for this data is of course App_Data. Think of a blog site (cough, SingleUserBlog, cough); all of the blog posts are going to be stored in the App_Data folder, perhaps as flat files or a database. And this is fine, because you don't serve those files directly - they're content to go in a page. But what about uploads? How can I include images in my blog? Uploading them is no problem, just chuck them in App_Data. But I can't serve them.

This is exactly the kind of solution a custom http handler is intended to solve. And the naive approach is to simply call HttpResponse.WriteFile and congratulate myself on a job well done.

So what's wrong with this?

Firstly, WriteFile reads the whole file into memory before chucking it to the client. For large files, it can fail. This isn't the best. But it can be worked around. I can use HttpResponse.TransmitFile to stream direct to the client. Or I could easily roll your own (this Microsoft KB article shows how).

Secondly, I'd have to add my own logic to setup the mime types. Boring, but still not reason enough to call it naive.

The third reason is the biggie. It's the single biggest mistake you see with custom http handler implementations, and that's forgetting caching and conditional gets. Bandwidth isn't free, and yet most http handlers will just serve the file. Again and again and again. To do things properly, I'd need to create and check etag values, and handle the various combination of the http headers (If-Unmodified-Since, Unless-Modified-Since, etc).

I could make this point into a blog post by itself. Fortunately, Kent Sharkey has already done it. Go read. Please.

Wouldn't it be nice if I could get someone else to do all this heavy lifting for me? (And I still haven't forgotten security.)

Tags:

asp.net

Comments

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading



About the author

Something about the author

Calendar

<<July 2010>>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

RecentComments

Comment RSS

License

Creative Commons License
Except where otherwise noted, content on this site is by Matt Ellis and is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

©2010 Matt Ellis