Espresso Tip: IHttpHandler and IsReusable

On December 12, 2011, in Uncategorized, by reverentgeek

Building an HttpHandler in .NET is an efficient way to serve specific types of HTTP requests. For example, dynamic images, dynamic script libraries, secured files, and Atom feeds are good candidates for using HttpHandlers.

When implementing the IHttpHandler interface, the read-only IsReusable property lets the server know whether or not an instance of your handler can be pooled and reused for other requests. Setting this property to true can be great for performance, but requires you to carefully consider two questions:

  1. Is the code thread safe?
  2. Does an instance of this HttpHandler have state or contextual information that would not apply or be completely wrong for another request?

I recently failed to consider the second question when building an HttpHandler for a multitenancy Web application. In a multi-tenant application, a single instance of an application is used to serve requests for multiple environments, each of which have distinct data that should be isolated from the others. For example, a multi-tenant application could be an online project management system where each organization has projects and users that are only visible to that organization. Obviously, you wouldn’t want your super-secret, million-dollar-idea project to “magically” appear on another organization’s project list!

In my case, the result was not as serious as that, but I did have to eat a little humble pie and roll back the application. Lesson learned. I hope this espresso-sized post helps you build better apps, and avoid the same mistake!

 
  • Daniel Fisher(lennybacon)

    Don’t do state at all in web apps. It violates the RFC spec :-)

    • Anonymous

      I should have stuck with “context” of the previous request :)

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1001

  • http://PauloMorgado.NET/ Paulo Morgado

    Why is thread safety an issue regarding IHttpModule.IsReusable?

    IHttpModule.IsReusable should be false when destructing the context of the previous request is more costly then creating a new instance of the handler.