为什么将String转换为Int32会在网站中随机失败

时间:2015-08-19 08:48:24

标签: c# .net sitecore

我有一段代码由于错误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 ...

5 个答案:

答案 0 :(得分: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);
  }
}

答案 1 :(得分:0)

欢迎来到一个不是每个人都拥有相同字母的世界。

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!
}

答案 2 :(得分:0)

尝试更改您的方法:

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

答案 3 :(得分:0)

很可能是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设置条件的断点。

答案 4 :(得分:0)

错误原因是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