views:

1712

answers:

4

I'm building an ASP.NET web application, and all of my strings are stored in a resource file. I'd like to add a second language to my application, and ideally, I'd like to auto-detect the user's browser language (or windows language) and default to that, instead of making them choose something besides English. Currently, I'm handling all the resource population manually, so adding a second resource file and language is trivial from my point of view, if I had an easy way to automatically figure out what language to display.

Has anybody done this, or do you have any thoughts about how I might retrieve that value? Since ASP.NET is server-based, I don't seem to have any access to specific browser settings.

RESOLUTION: Here's what I ended up doing. I used a "For Each" to go through "HttpContext.Current.Request.UserLanguages" and search for one I support. I'm actually just checking the left two characters, since we don't support any dialects yet - just English and Spanish. Thanks for all the help!

+1  A: 

This article might be helpful with auto detecting the browser's language setting.

[EDIT] Yes. The quoted article does not use ASP.NET. This article does.

Vincent Ramdhanie
this is a ASP solution, not an ASP.NET one, right?
Serge - appTranslator
Though it's not .NET, I found the first article way more informative than the second, and it moved me in the right direction.
rwmnau
A: 

This is a great question, as localization in Asp.Net is overlooked by many developers.

Asp.Net SHOULD automatically pick up on the user's browser settings and force the CultureInfo.CurrentCulture to the user's browser language. You can force the issue with a line in Page_OnInit() like:

Thread.CurrentThread.CurrentCulture = new CultureInfo(HttpContext.Current.Request.UserLanguages[0]);

How can you test this? Enter the languages panel on our browser and change settings.

Jeff Fritz
+5  A: 

Try this in the web.config:

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

This will cause ASP.NET to auto-detect the client's culture from the request header. You can also set this on a per-page basis via the Page attribute.

maxam: I wrapped your code in a formatted code block to show the <>s. "edit" the response to see how this looks, if you're interested.
Blair Conrad
Thanks, much appreciated!
+1  A: 

The client generally sets Accept-Language in the HTTP request header with a quantitatively scored list of preferred language, conventionally (but not necessarily) in order of most favored to least favored. You can parse that, but as Maxam has noted, ASP.Net does have a mechanism for doing that on your behalf.

JasonTrue