如何在TempData中存储与读取decimal类型数据?
解决TempData无法存储decimal类型的问题
ASP.NET Core默认的DefaultTempDataSerializer不支持直接序列化System.Decimal类型,直接存储decimal会触发你遇到的序列化错误,下面是两种实用的解决方法:
方法一:转字符串存取(最简单直接)
把decimal转成字符串存储,读取时再解析回decimal,建议用固定文化格式避免不同地区的格式差异导致解析失败:
存储代码
// 使用InvariantCulture确保格式统一 TempData["PromocodeDiscount"] = 5.00m.ToString(System.Globalization.CultureInfo.InvariantCulture);
读取代码
decimal discount = 0; // 先判断类型再解析,避免空引用或类型转换错误 if (TempData["PromocodeDiscount"] is string discountStr) { decimal.TryParse(discountStr, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out discount); }
方法二:用自定义类包装(适合复杂场景)
如果需要存储多个和折扣相关的值,或者想保持类型安全,可以把decimal包装在一个简单的POCO类里:
定义包装类
public class DiscountInfo { public decimal DiscountValue { get; set; } }
存储代码
TempData["PromocodeDiscount"] = new DiscountInfo { DiscountValue = 5.00m };
读取代码
decimal discount = 0; if (TempData["PromocodeDiscount"] is DiscountInfo discountInfo) { discount = discountInfo.DiscountValue; }
注意:自定义类需要是公共类,属性为可读写的,默认序列化器能正常处理这类简单对象。
内容的提问来源于stack exchange,提问作者Alice
相关产品推荐
相关产品推荐

