views:

225

answers:

1

I'm creating an HttpModule that needs to know the value of Thread.CurrentThread.CurrentCulture as set in an MVC application. That value is currently being set by the BaseController, but when my HttpModule.PostRequestHandlerExecute() method fires, it reverts to what the Culture was prior to page rendering.

I have duplicated this by creating a simple web app with these steps:

  1. Module.PreRequestHandlerExecute: Set culture to A
  2. Page_Load: Culture is currently A. Set culture to B
  3. Module.PostRequestHandlerExecute: Current thread culture is A. I expected it to be B but it was changed between page rendering and PostRequestHandlerExecute

Any idea why .Net changes this value or how I could get around it? The thread is the same, so something in .Net must be explicitly reverting the culture.

+2  A: 

If you simply set the culture for a running thread any operation that results in a thread switch (such as another part of the page lifecycle in asp.net) would result in reversion to the default culture.

The recommended approach is here ...

http://msdn.microsoft.com/en-us/library/bz9tc508.aspx

This page discusses 3 options ...

  1. Setting the culture for the entire application.
  2. Setting the culture at page level.
  3. Setting the culture programmatically per request.

It's worth noting that any modules are loaded as part of a page request so changing the culture at page level should change it for all modules on that request.

Wardy
It *should* change the locale for all modules on the request, but it doesn't. That's the problem. See step 3 in the original question. There is no thread switching between page rendering and the post-request firing in the module.
Chad
there's no thread switching in your code but you can't garantee that in the .Net code. I believe you need to set the culture at the request level and not the thread level which my answer solves. In other words, setting or getting the culture on the current thread will not give you what you want. you need to configure the whole request and the way to do that is to implement the init culture event manually by overriding. ... Do you understand?
Wardy