【问题标题】:Input string was not in a correct format MVC输入字符串的格式不正确 MVC
【发布时间】:2016-05-15 20:28:09
【问题描述】:

我只想将 Session["Price"] 转换为十进制并将 Session["Count"] 转换为整数

        doc.Price = Convert.ToDecimal(Session["Price"]);
        doc.Count = Convert.ToInt16(Session["Count"]); 

我收到此错误

【问题讨论】:

  • 显然Session["Price"] 中的任何值都不能直接转换为小数。
  • 如果 Session 变量没有定义,或者是一个空字符串或者不是一个数值,你认为会发生什么。请使用您的调试器,您很快就会找到原因

标签: asp.net-mvc linq entity-framework-4


【解决方案1】:
var stringValue = Session["Price"].ToString();
if(!string.IsNullOrEmpty(stringValue)) {
    try {
       doc.Price = Convert.ToDecimal(stringValue);
    }
    catch(formatExecption ex) {
        // Should not have gotten here because the frontend should gaurd against input values that are not number but anyway
       throw new ValidationExecption("Price is not a number");
}

您在这里遇到的整体问题是您没有练习防御性编码。去学习防御性编码,它将提高你的代码质量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-08-22
    相关资源
    最近更新 更多