This project has moved. For the latest updates, please go here.

Why does OWIN create my handler multiple times per http request?

Sep 25, 2014 at 4:08 PM
Edited Sep 25, 2014 at 4:22 PM
I'm developing a custom authentication OMC and trying to maintain state per http request but it's not working. It's clear that MS OWIN is calling the CreateHandler() method on my middleware class exactly 5 times per http request which means my handler class is also created 5 times and therefore no state is shared between instances.

I've tried shoving things into the context like Context.Set() & Context.Get() to maintian state between instances but it doesn't work either since each of my handler instances receives a fresh context. I've also tried to play with the PipelineStage for my middleware, but regardless of the value my handler is instantiated exactly 5 times.
  1. What's going on under the covers that is causing MS OWIN to instantiate my handler this many times per http request?
  2. Why wouldn't it just call it exactly once?
  3. How can I maintain state per http request in OWIN?
Sep 25, 2014 at 4:24 PM
CreateHandler should only be called once per request as you expect. The only place it gets called is AuthenticationMiddleware.Invoke. The context will always be the same for a given request.

Note that one request from the client may trigger multiple automatic redirects depending on the type of auth you're using, each of which is a new http request to the server. Browsers also send extra requests for things like the favicon.ico, css files, etc.. If you compare the requests you should find that they have different paths, queries, headers, and/or bodies.
Sep 25, 2014 at 5:14 PM
Ah-ha, thanks! That was driving me crazy. Each time the request's Path was different so that makes sense now.