0

I have a REST service that generates string messages with currencies and dates, so I need the right culture to be set up. Messages are produced in different steps that runs between asynchronous operations.

Web API will set the culture coming in the Accept-Language header if such feature is configured in the Web.config:

<globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto" />

After some testing it seems that the culture got by Web API this way is consistent across async/await operations. I wonder if it will behave the same way when on self-host...

However, I would like to know how to change the culture of the request arbitrarily in a way that flows correctly in the SynchronizationContext used by the host. I think it should be possible because as I said, the one adquired from the Accept-Language header using enableClientBasedCulture="true" seems to flow correctly.

For example, AspNetSynchronizationContext flows it through HttpContext.Current, so if Thread.CurrentThread.CurrentCulture and/or Thread.CurrentThread.CurrentUICulture are manipulated, their culture may change after an await. So this way is not safe for async/await.

What I am looking for is not the culture awaiter from Stephen Toub, but the way of forcing Web API to change the request's culture to something else.

I have tried with a delegating handler, changing the Accept-Language in the request message, but it seems too late and it has no effect on Thread.CurrentThread.CurrentCulture and/or Thread.CurrentThread.CurrentUICulture.

Is there a way of doing this in a safe async/await way?

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • Why don't you pass the culture to your code instead of relying on some singleton? – Paulo Morgado Jan 30 '17 at 17:23
  • Because I expect it to be a cross cutting concern. Otherwise I would have to pass the culture in each method, and set the `CurrentCulture` and `CurrentUICulture` properties of the `Thread` in the header of each method. – vtortola Jan 30 '17 at 18:54

0 Answers0