c# - Culture 和 NullReferenceException 有问题

标签 c# redirect cultureinfo

我正在尝试编写着陆页代码,通过阅读 Culture 来决定是将请求重定向到英文网站还是斯洛伐克语网站。

代码如下:

public partial class _default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strCountry = ResolveCountry().ToString();
        if (strCountry == "SK")
        {
            Response.Redirect("/sk/");
        }
        else
        {
            Response.Redirect("/en/");
        }
    }

    public static CultureInfo ResolveCulture()
    {
        string[] languages = HttpContext.Current.Request.UserLanguages;

        if (languages == null || languages.Length == 0)
            return null;

        try
        {
            string language = languages[0].ToLowerInvariant().Trim();
            return CultureInfo.CreateSpecificCulture(language);
        }
        catch (ArgumentException)
        {
            return null;
        }
    }

    public static RegionInfo ResolveCountry()
    {
        CultureInfo culture = ResolveCulture();
        if (culture != null)
            return new RegionInfo(culture.LCID);

        return null;
    }
}

问题是在浏览器中它看起来没问题,它会将您重定向到站点:http://www.alexmolcan.sk

但是在查看IIS日志时,谷歌站长工具还是http://www.rexswain.com/httpview.html我总是收到 500 ASP 错误:

 Object·reference·not·set·to·an·instance·of·an·object.
 System.NullReferenceException:·Object·reference·not·set·to·an·instance·of·an·object.

响应头:

HTTP/1.1·500·Internal·Server·Error
Connection:·close
Content-Length:·4684

当我在本地调试项目时,它总是可以毫无问题地编译。我不知道我做错了什么

谢谢。

编辑

异常

Process information: 
   Process ID: 4068 
   Process name: w3wp.exe 
   Account name: IIS APPPOOL\ASP.NET v4.0 

Exception information: 
   Exception type: NullReferenceException 
   Exception message: Object reference not set to an instance of an object.
   at sk_alexmolcan._default.Page_Load(Object sender, EventArgs e) in default.aspx.cs:line 15
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean  includeStagesAfterAsyncPoint)

最佳答案

我认为您正在抛出,因为当 ResolveCountry 返回 null 时,您的 .ToString() 和 if(strcountry == "SK") 将抛出。

无法将 null 转换为字符串。尝试

CultureInfo cul = ResolveCountry();
string strCountry = cul== null ? string.empty : cul.ToString();

if (strCountry == "SK") {}

关于c# - Culture 和 NullReferenceException 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181852/

相关文章:

jquery - Ajax 重定向处理

asp.net-mvc-3 - MVC3 为每个请求改变文化的正确方法

c# - 检查字符串的一部分是否匹配正则表达式

c++ - 如何处理 C++ 重定向进程的输出

apache - 使用 .htaccess 重写规则重定向到我服务器上的不同文件夹

c# - 如果我指定了确切的结构,为什么 TryParseExact 需要 CultureInfo?

.net - MonoTouch CurrentUI文化

c# - 如何实现具有公共(public)属性但私有(private)设置方法的多个接口(interface)?

c# - 如何使用 C# 在用户控制页面中获取父页面名称

c# - 连接到服务器 vs 连接到数据库