【问题标题】:Why Convert String to Int32 fails randomly in Website为什么将字符串转换为 Int32 在网站中随机失败
【发布时间】:2015-08-19 08:48:23
【问题描述】:

由于错误System.FormatException,我有一些代码有时会失败。据我了解,如果UserId 不为空,那么默认0 应该从下面的方法GetUserProperty 返回,我知道(并且对此毫无疑问)系统中的UserId 将是某个数字或为空,它永远不会是非数字的。

代码如下:

private void SomeMethod()
{
    var userId = Convert.ToInt32(GetUserProperty("UserId", "0"));
    // Do something with userId..
}

public string GetUserProperty(string propertyName, string defaultValue = "")
{
    var propertyValue = SecurityUtil.GetUserProperty(propertyName);
    return !string.IsNullOrWhiteSpace(propertyValue) ? propertyValue : defaultValue;
}

系统日志中的 StackTrace 说:

System.FormatException: Input string was not in a correct format. 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 ...

【问题讨论】:

  • Convert.ToInt32(string) 如果输入是表示有效整数的字符串,则永远不会失败 - 所以它不会随机失败。您需要找出为什么 GetUserProperty("UserId", "0") 不是有效的整数表示。
  • @un-lucky: 如果你传入null 引用,Convert.ToInt32 返回 0。但是,它不会处理 empty 字符串。
  • @Phill:是的,但这不是用空字符串调用Convert.ToInt32,是吗?
  • @Phill: 是的,但我和我都不是不走运的。我们只是谈论涉及的Convert.ToInt32 电话。请查看 cmets:“Convert.ToInt32()` 无法处理 null”和“如果传入 null 引用,Convert.ToInt32 返回 0。但是,它不会处理空字符串。”
  • @Phill:请再次阅读我的评论 - 以及之前的 cmets。不幸的是,Convert.ToInt32 无法处理空引用。我说它可以,但它不能处理空字符串。然后你给我发了一条评论说“它可以很好地处理一个空字符串”显然错过了不能处理空字符串的Convert.ToInt32的上下文......然后在09:39:13Z没有阅读我的解释。

标签: c# .net sitecore


【解决方案1】:

可能SecurityUtil.GetUserProperty(propertyName) 正在返回一个无法解析为 int 的值。

像这样修改SomeMethod()

private void SomeMethod()
{
  int userId = 0;
  string userProperty = GetUserProperty("UserId", "0");

  if(int.TryParse(userProperty , out userId)){
      // Do something with userId..
  }
  else{
    //Do something with the exception
      //Console.Write("Invalid property value {0}", userProperty);
//Sitecore.Diagnostics.Log.Info("Invalid property value " + userProperty.ToString(), this);
  }
}

【讨论】:

  • int userId 0; 实际上应该是 int userId = 0;。这是一个错字。
  • Change Console.Write with Sitecore.Diagnostics.Log.Info("无效的属性值 " + userProperty.ToString(), this);因为这个问题与 Sitecore 有关。而且 Sitecore 是网站,不能与控制台一起使用。
  • 我发现了问题。确实是 SecurityUtil.GetUserProperty 返回了不正确的值。感谢您对此的支持。
【解决方案2】:

欢迎来到一个并非所有人都使用相同字母的世界。

CurrentCulture 在您的情况下可能是 UI 文化,因此不可靠。可能是 f.ex。中文取决于您的用户:-)

处理这个问题的更好方法是明确设置文化。

int value;
if (!int.TryParse(GetUserProperty("UserId", "0"), 
    NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
   // make / throw your own error message with details on the user property!
}

【讨论】:

    【解决方案3】:

    尝试像这样改变你的方法:

    public string GetUserProperty(string propertyName, string defaultValue = "")
    {
        var propertyValue = SecurityUtil.GetUserProperty(propertyName);
        return Array.TrueForAll(propertyValue .ToCharArray(), c => Char.IsDigit(c)) ? propertyValue : defaultValue;
    }
    

    【讨论】:

      【解决方案4】:

      很可能是 GetUserPropery 返回了一个无效的整数。 试试这个(如果你的值可以像 23.5,使用正则表达式来验证字符串):

      private void SomeMethod()
      {
          var userIdStr =GetUserProperty("UserId", "0");
          Debug.Assert(userIdStr.All(char.IsDigit));
          var userId = Convert.ToInt32(userIdStr);
          // Do something with userId..
      }
      

      或者使用 Int.TryParse 放置一个带有 Condition 的断点。

      【讨论】:

        【解决方案5】:

        错误原因是SecurityUtil.GetUserProperty()方法,因为它可能无法转换为Convert.ToInt32()

        public string GetUserProperty(string propertyName, string defaultValue = "")
        {
            var propertyValue = SecurityUtil.GetUserProperty(propertyName); // Why used var maybe because its not convertible to integer?
            return !string.IsNullOrWhiteSpace(propertyValue) ? propertyValue : defaultValue; // If this is true and propertyValue is not convertible to Int32, System.FormateException will be occurred.
        }
        

        就像我小提琴中的例子:http://goo.gl/GMP5tH

        【讨论】:

        • 我发现了问题。确实是 SecurityUtil.GetUserProperty 返回了不正确的值。感谢您对此的支持。
        • @HarshBaid 很高兴知道:D
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-24
        • 2017-01-19
        • 2019-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多