C#。加载错误 - System.ArgumentNullException:

时间:2018-04-20 16:35:32

标签: c# asp.net webforms

以下代码在localhost上正常工作,但在发布功能后也不起作用,它返回以下错误。 有什么想法吗?

"Load bug - System.ArgumentNullException: Value cannot be null. Parameter name: String
    at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)  
    at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)  
    at Main.Page_Load(Object sender, EventArgs e) in C:\Users\xyz\source\repos\zyc\bgfn\Main.aspx.cs:line 38"
if (!IsPostBack)
{
    try
    {
        if (ConfigurationManager.AppSettings.Keys.Count < 3)
        {
            ConfigurationManager.AppSettings["saved"] = DateTime.Now.ToShortTimeString();
            ConfigurationManager.AppSettings["houseLeft"] = "60";
            ConfigurationManager.AppSettings["carLeft"] = "30";
        }

        // PROBLEM IS THAT REPUBLISHING WILL RESET THE CONFIG AND HENCE ALL THE OFFERS - MOVE COUNTS TO DB

        int houseLeft = int.Parse(ConfigurationManager.AppSettings["houseLeft"]);

        int carLeft = int.Parse(ConfigurationManager.AppSettings["carLeft"]);

        ConfigurationManager.AppSettings["houseLeft"] = houseLeft.ToString();
        ConfigurationManager.AppSettings["carLeft"] = carLeft.ToString();

        redeemOne.Text = houseLeft + " left";
        redeemTwo.Text = carLeft + " left";
    }
    catch (Exception exc)
    {
        lblDebug.Text = "Load bug - " + exc.ToString();
        redeemOne.Text = "0" + " left";
        redeemTwo.Text = "0" + " left";
    }
}

2 个答案:

答案 0 :(得分:0)

看起来你有ConfigurationManager.AppSettings [&#34; houseLeft&#34;]和/或ConfigurationManager.AppSettings [&#34; carLeft&#34;]为null。您可能想要检查null或者使用try catch来处理参数null异常

答案 1 :(得分:0)

尝试检查单键,而不是检查键数?任何人都可以添加/更改appsettings到app.config ...:)

 if (ConfigurationManager.AppSettings["saved"] == null)
      ConfigurationManager.AppSettings["saved"] = DateTime.Now.ToShortTimeString();
 if (ConfigurationManager.AppSettings["houseLeft"] == null)
      ConfigurationManager.AppSettings["houseLeft"] = "60";
 if (ConfigurationManager.AppSettings["carLeft"] == null)
     ConfigurationManager.AppSettings["carLeft"] = "30";

此外,我会安全地尝试转换以避免异常 - 等于app.config中的设置:

if(!int.TryParse(ConfigurationManager.AppSettings["houseLeft"], out int houseLeft))
{
   //handle error...eg. setting a default value
  ConfigurationManager.AppSettings["houseLeft"] = "60";
}