.NET:应用文化信息时出现 NullReferenceException

发布于 2024-10-05 13:13:31 字数 3109 浏览 1 评论 0原文

这个错误让我发疯。 我正在构建一个可以在多种语言之间切换的选项的网站。

这是该网站的(非常)基本结构:
Default.aspx(带有代码隐藏文件)
Shared/Default.Master(带有代码隐藏文件)
App_Code/BasePage.cs
App_LocalResources/Default.aspx.en.resx

Default.aspx 使用母版页。
BasePage.cs:BasePage类派生自System.Web.Ui.Page(公共类BasePage:Page)
Default.aspx.cs:Default 派生自 BasePage (公共分部类 Default :BasePage)

所有这些都运行良好。

然后我尝试重写 InitializeCulture() 方法,以便可以更改网站的语言。 区域性应采用两个字母的形式(因此“en”而不是“en-US”等)。

BasePage.css 文件如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Threading;
using System.Globalization;

namespace Web
{
public class BasePage : Page
{
    protected override void InitializeCulture()
    {
        LanguageQS = Request.QueryString["l"].ToString();

        // Language
        if( !String.IsNullOrEmpty( LanguageQS ) )
        {
            // Validate the QueryString Value
            string[] LanguagesArray = ConfigurationManager.AppSettings["Languages"].ToString().Split( ',' );
            if( LanguagesArray.Contains( LanguageQS ) )
            {
                Session["Language"] = LanguageQS;
                cultureString = LanguageQS;
            }
        }
        else if( Session.IsNewSession || String.IsNullOrEmpty( Session["Language"].ToString() ) )
        {
            // New Session, set default Language
            cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();
        }
        else
        {
            // Get language from session
            cultureString = Session["Language"].ToString();
        }

        // Set the language
        try
        {

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
            Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );
        }
        catch { throw; }

        base.InitializeCulture();
    }

    private string _culture;
    public string cultureString
    {
        set { this._culture = value; }
        get { return this._culture; }
    }

    private string _languageQS;
    public string LanguageQS
    {
        set { this._languageQS = value; }
        get { return this._languageQS; }
    }
}

}

现在,当我打开页面时,出现以下错误:

Line 1:  <%@ Page Language="C#" MasterPageFile="~/Shared/Default.Master" Inherits="Default" meta:resourcekey="PageResource" Codebehind="Default.aspx.cs" AutoEventWireup="True" %>

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

我将错误追溯到这两行:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );

如果删除它们,一切都会再次正常工作。
但即使我把

cultureString = "en";

cultureString = "en-US";

放在这些行前面,我也会得到 NullException。

有人有提示吗?

我对 .NET 开发还很陌生,无法找到导致此错误的原因。

this error is driving me nuts.
Im building a website with the option to change between multiple languages.

Heres the (very) basic structure of the site:
Default.aspx (with CodeBehind-File)
Shared/Default.Master (with CodeBehinde-File)
App_Code/BasePage.cs
App_LocalResources/Default.aspx.en.resx

Default.aspx uses the Masterpage.
BasePage.cs: The BasePage class derivates from System.Web.Ui.Page (public class BasePage : Page)
Default.aspx.cs: Default derivates from BasePage (public partial class Default : BasePage)

All that works well.

Then I tried to override the InitializeCulture() Method to make it possible to change the language of the site.
The culture should be in two-letter form (so "en" not "en-US" etc.).

This is how the BasePage.css File looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Threading;
using System.Globalization;

namespace Web
{
public class BasePage : Page
{
    protected override void InitializeCulture()
    {
        LanguageQS = Request.QueryString["l"].ToString();

        // Language
        if( !String.IsNullOrEmpty( LanguageQS ) )
        {
            // Validate the QueryString Value
            string[] LanguagesArray = ConfigurationManager.AppSettings["Languages"].ToString().Split( ',' );
            if( LanguagesArray.Contains( LanguageQS ) )
            {
                Session["Language"] = LanguageQS;
                cultureString = LanguageQS;
            }
        }
        else if( Session.IsNewSession || String.IsNullOrEmpty( Session["Language"].ToString() ) )
        {
            // New Session, set default Language
            cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();
        }
        else
        {
            // Get language from session
            cultureString = Session["Language"].ToString();
        }

        // Set the language
        try
        {

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
            Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );
        }
        catch { throw; }

        base.InitializeCulture();
    }

    private string _culture;
    public string cultureString
    {
        set { this._culture = value; }
        get { return this._culture; }
    }

    private string _languageQS;
    public string LanguageQS
    {
        set { this._languageQS = value; }
        get { return this._languageQS; }
    }
}

}

Now I get the following error when I open the Page:

Line 1:  <%@ Page Language="C#" MasterPageFile="~/Shared/Default.Master" Inherits="Default" meta:resourcekey="PageResource" Codebehind="Default.aspx.cs" AutoEventWireup="True" %>

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

I traced the error down to these two rows:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture( cultureString );
Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureString );

If I remove them all works well again.
But even if I put

cultureString = "en";

or

cultureString = "en-US";

right in front of those lines I get that NullException.

Anyone got a hint?

Im pretty new to .NET-Development and cant find whats causing this error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

想你只要分分秒秒 2024-10-12 13:13:31

谢谢大家。

我最大的过失是在发布到这里之前没有检查调试器。 :(

调试器告诉我

LanguageQS = Request.QueryString["l"].ToString();

失败了,因为没有给出 QuerySting 并且 ToString() 无法将 null 转换为字符串。

修复了这个问题。

感谢有关返回路径的提示。也修复了这个问题。

Thanks everyone.

My biggest culpa is not checking the debugger before posting here. :(

Debugger told me that

LanguageQS = Request.QueryString["l"].ToString();

failed, because no QuerySting was given and ToString() cant convert null to a string.

Fixed that.

Thanks for the hint on the return paths. Fixed that as well.

北陌 2024-10-12 13:13:31

对我来说,下面的代码

private string _culture; 
    public string cultureString { 
        set { this._culture = value; }
        get { return this._culture; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        cultureString = "en";
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureString);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureString);
    }

只有在cultureString设置为null时上面的代码才会失败;所以请检查该场景

for me below code works

private string _culture; 
    public string cultureString { 
        set { this._culture = value; }
        get { return this._culture; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        cultureString = "en";
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureString);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureString);
    }

only possibility for above code to fail if cultureString is set to null; so please check that scenario

つ可否回来 2024-10-12 13:13:31

还要在此处设置 Session["Language"] :

// New Session, set default Language
        cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();

Session["Language"] =cultureString

因为在最后的 else 中你正在使用它:)

Also set the Session["Langugage"] here :

// New Session, set default Language
        cultureString = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();

Session["Language"] = cultureString

Because in the final else you are using it :)

相对绾红妆 2024-10-12 13:13:31

在您的代码中,有些路径未分配 cultureString 值,例如在 LanguagesArray 中找不到 LanguageQS

在将 Session["Language"] 分配给 cultureString 之前,还要确保它不为 null。

In your code there are paths where cultureString is not assigned a value, e.g. where LanguageQS is not found in LanguagesArray.

Also ensure that Session["Language"] is not null before assigning it to cultureString.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文