elo*_*los 52 c# tempdata asp.net-core-mvc asp.net-core
我一直试图通过使用TempData重定向后将数据传递给一个动作,如下所示:
if (!ModelState.IsValid)
{
TempData["ErrorMessages"] = ModelState;
return RedirectToAction("Product", "ProductDetails", new { code = model.ProductCode });
}
Run Code Online (Sandbox Code Playgroud)
但不幸的是,它失败了以下消息:
"
System.InvalidOperationException的Microsoft.AspNet.Mvc.SessionStateTempDataProvider'不能序列类型的对象'ModelStateDictionary'到会话状态".
我在Github的MVC项目中发现了一个问题,但是虽然它解释了为什么我收到这个错误,但我看不出什么是可行的替代方案.
一种选择是将对象序列化为json字符串,然后将其反序列化并重新构建ModelState.这是最好的方法吗?我需要考虑哪些潜在的性能问题?
最后,是否有任何替代方法可以序列化复杂对象或使用其他不涉及使用的模式TempData?
hem*_*hem 110
您可以像这样创建扩展方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并且,您可以按如下方式使用它们:
说objectA是类型ClassA.你可以使用上面提到的扩展方法将它添加到临时数据字典中,如下所示:
TempData.Put("key", objectA);
要检索它,你可以这样做:
var value = TempData.Get<ClassA>("key")
其中value检索将型ClassA
在 .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);
}
}
Run Code Online (Sandbox Code Playgroud)
我无法发表评论,但我也添加了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);
}
Run Code Online (Sandbox Code Playgroud)
例
var value = TempData.Peek<ClassA>("key") where value retrieved will be of type ClassA
Run Code Online (Sandbox Code Playgroud)