简体   繁体   English

为什么将字符串转换为Int32在网站中随机失败

[英]Why Convert String to Int32 fails randomly in Website

I have some piece of code which fails at times due to error System.FormatException . 我有一些代码有时由于错误System.FormatException而失败。 In my understanding if the UserId is not empty then default 0 should be returned from below method GetUserProperty and I know (and have not doubt on this) that UserId in the system will be either some number or empty, it will never be anything non-numeric. 根据我的理解,如果UserId不为空,则应从下面的GetUserProperty方法返回默认值0并且我知道(并且对此毫无疑问)系统中的UserId可以是数字或为空,它永远不会是非-数字。

Code as below: 代码如下:

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 in the system log says: 系统日志中的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 ...

Probably SecurityUtil.GetUserProperty(propertyName) is returning a value that cannot be parsed into an int. 可能SecurityUtil.GetUserProperty(propertyName)返回的值无法解析为int。

modify SomeMethod() like this 像这样修改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);
  }
}

Welcome to an world where not everyone shares the same alphabet. 欢迎来到一个并非所有人共享同一字母的世界。

CurrentCulture is probably the UI culture in your case and therefore unreliable. 在您的情况下, CurrentCulture可能是UI文化,因此不可靠。 It might be f.ex. 可能是f.ex. chinese depending on your user :-) 中文取决于您的用户:-)

The better way to handle this is to explicitly set the culture. 处理此问题的更好方法是显式设置文化。

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

Try to change your method like this: 尝试像这样更改您的方法:

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

Very probably it's the GetUserPropery which returns an invalid integer. 很可能是GetUserPropery返回无效的整数。 Try this ( if your value can be like 23.5, use a Regex instead to validate the string ): 尝试以下操作(如果您的值可以是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..
}

Or put a breakpoint with a Condition using Int.TryParse. 或使用Int.TryParse将断点置于条件中。

The error cause is the SecurityUtil.GetUserProperty() method, because maybe its not convertible to Convert.ToInt32() . 错误原因是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.
}

Just like example in my fiddle: http://goo.gl/GMP5tH 就像我的小提琴中的示例一样: http : //goo.gl/GMP5tH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM