将复杂对象存储在TempData

时间:2016-01-06 17:14:06

标签: c# asp.net-core asp.net-core-mvc tempdata

我一直在尝试使用TempData重定向后将数据传递给动作,如下所示:

if (!ModelState.IsValid)
{
    TempData["ErrorMessages"] = ModelState;
    return RedirectToAction("Product", "ProductDetails", new { code = model.ProductCode });
}

但不幸的是,它失败了以下消息:

  

'System.InvalidOperationException   Microsoft.AspNet.Mvc.SessionStateTempDataProvider'无法序列化   'ModelStateDictionary'类型的对象到会话状态。'

我在the MVC project in Github中发现了一个问题,但虽然它解释了为什么我收到此错误,但我看不出什么是可行的替代方案。

一个选项是将对象序列化为json字符串,然后将其反序列化并重新构建ModelState。这是最好的方法吗?我需要考虑哪些潜在的性能问题?

最后,是否有任何替代方法可以序列化复杂对象或使用其他不涉及使用TempData的其他模式?

3 个答案:

答案 0 :(得分:90)

您可以像这样创建扩展方法:

public static class TempDataExtensions
{
    public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
    {
        tempData[key] = JsonConvert.SerializeObject(value);
    }

    public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
    {
        object o;
        tempData.TryGetValue(key, out o);
        return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
    }
}

并且,您可以按如下方式使用它们:

objectA的类型为ClassA。您可以使用上面提到的扩展方法将其添加到临时数据字典中,如下所示:

TempData.Put("key", objectA);

要检索它,你可以这样做:

var value = TempData.Get<ClassA>("key") 检索到的value类型为ClassA

答案 1 :(得分:5)

我无法评论,但我添加了一个PEEK,这很好检查是否有读取而不是删除下一个GET。

public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : class
{
    object o = tempData.Peek(key);
    return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}

实施例

var value = TempData.Peek<ClassA>("key") where value retrieved will be of type ClassA

答案 2 :(得分:5)

在.Net core 3.1及更高版本中使用System.Text.Json

using System.Text.Json;

    public static class TempDataHelper
    {
        public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
        {
            tempData[key] = JsonSerializer.Serialize(value);
        }

        public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            tempData.TryGetValue(key, out object o);
            return o == null ? null : JsonSerializer.Deserialize<T>((string)o);
        }

        public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            object o = tempData.Peek(key);
            return o == null ? null : JsonSerializer.Deserialize<T>((string)o);
        }
    }
相关问题