输入字符串的格式不正确 MVC

Input string was not in a correct format MVC

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

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

我收到这个错误

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");
}

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