我正在尝试使用临时数据返回消息,但它给出了一个错误:
InvalidOperationException:“ Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer”无法序列化类型的对象
我已经在使用
services.AddMvc().AddSessionStateTempDataProvider();
app.UseSession()
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
这是我共享的
FlashMessages.cshtml:
@using EnduroMotors.ViewModels
@{
var errorMessages = TempData["_error_messages"] as List<FlashMessageModel>
?? new List<FlashMessageModel>();
var warningMessages = TempData["_warning_messages"] as
List<FlashMessageModel> ?? new List<FlashMessageModel>();
var successMessages = TempData["_success_messages"] as
List<FlashMessageModel> ?? new List<FlashMessageModel>();
var infoMessages = TempData["_info_messages"] as List<FlashMessageModel> ??
new List<FlashMessageModel>();
}
这是我的视图模型:
FlashMessageModel
public class FlashMessageModel
{
public string Title { get; set; }
public string Message { get; set; }
}
这是在控制器中使用的:
控制器
protected void ShowSuccessMessage(string message, string title =
"Success!")
{
var messages =
(List<FlashMessageModel>)TempData["_success_messages"] ?? new
List<FlashMessageModel>();
messages.Add(new FlashMessageModel
{
Title = title,
Message = message
});
TempData["_success_messages"] = messages;
}
与此结合使用
ShowSuccessMessage("You have completed.");
它应该在带有@{Html.RenderPartial("FlashMessages");}
的索引中显示成功消息,但会显示
InvalidOperationException:'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer'无法序列化'EnduroMotors.ViewModels.FlashMessageModel'类型的对象。 Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer.EnsureObjectCanBeSerialized(对象项)
答案 0 :(得分:0)
TempData将对象序列化为字符串以进行存储。它本地支持字符串,整数和布尔类型。如果要存储更复杂的类型,则必须自己序列化(和反序列化)它们。 JSON是推荐的格式。以下扩展方法使用JSON.NET JsonConvert
静态方法执行此操作:
public static class TempDataExtensions
{
public static void Set<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
{
tempData.TryGetValue(key, out object o);
return o ?? JsonConvert.DeserializeObject<T>((string)o);
}
}
您可以在此处了解更多信息:https://www.learnrazorpages.com/razor-pages/tempdata#limitations