簡體   English   中英

為什么將字符串轉換為Int32在網站中隨機失敗

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

我有一些代碼有時由於錯誤System.FormatException而失敗。 根據我的理解,如果UserId不為空,則應從下面的GetUserProperty方法返回默認值0並且我知道(並且對此毫無疑問)系統中的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 ...

可能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);
  }
}

歡迎來到一個並非所有人共享同一字母的世界。

在您的情況下, 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!
}

嘗試像這樣更改您的方法:

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

很可能是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將斷點置於條件中。

錯誤原因是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM