views:

578

answers:

2

We have a multilingual site that utilizes asp.net 2.0 cultures. The current culture is set through the url rewritten as a query string. (~/es/blah.aspx is the spanish version of ~/blah.aspx - rewritten as ~/blah.aspx?lang=es)

The code that tests the culture is as follows:

    System.Globalization.CultureInfo ci;
    try
    {
        ci = new System.Globalization.CultureInfo(Request.QueryString["lang"] ?? string.Empty);
    }
    catch
    {
        ci = new System.Globalization.CultureInfo(string.Empty);
    }

If there is no culture set, it defaults to english, 127. When there is a culture, all links on that page are then pre-pended with the correct culture name.

Some how or another a spider got a hold of a few links in the form of ~/www.test.com/blah.aspx and is hammering our site with a culture of www.test.com which and flooding our error logging.

Is there any way to test whether a culture name is valid besides catching an exception?

+1  A: 

This site has an example using LINQ:

CultureInfo[] cultures = System.Globalization.CultureInfo.GetCultures
                         (CultureTypes.SpecificCultures);

var selectCulture = from p in cultures
                    where p.Name == value
                    select p;

if (selectCulture.Count() == 1)
{
    // your culture is good
}

It seems a bit heavy, though. I'd probably stick with what you have.

Michael Haren
Thanks, but I should have mentioned we're still on .net 2.0
You can pull out the parts you need. Roger turned it into .net 2.0 for you.
Michael Haren
+3  A: 

You don't have to use LINQ:

private static bool IsValidCultureName(string cultureName)
{
    CultureInfo[] cultures =
        CultureInfo.GetCultures(CultureTypes.SpecificCultures);
    foreach (CultureInfo culture in cultures)
    {
        if (culture.Name == cultureName)
            return true;
    }

    return false;
}

This could be quite expensive, but possibly still cheaper than dealing with exceptions, which are quite expensive -- measure the difference before taking my word for it, though.

I don't think that the list of defined cultures will change between .NET releases, so you should probably get the list at startup and cache it somewhere.

Roger Lipscombe
+1, nice work. I still think it's probably over kill to do this, though.
Michael Haren