Asp.Net核心Tempdata和redirecttoaction无法正常工作

时间:2019-06-10 14:38:03

标签: asp.net-core-2.2 tempdata redirecttoaction

我的basecontroller类中有一个方法,可以将数据添加到tempdata中以显示弹出消息。

protected void AddPopupMessage(SeverityLevels severityLevel, string title, string message)
{
    var newPopupMessage = new PopupMessage()
    {
        SeverityLevel = severityLevel,
        Title = title,
        Message = message
    };
    _popupMessages.Add(newPopupMessage);
    TempData["PopupMessages"] = _popupMessages;
}

如果操作返回一个视图,则可以正常工作。如果该操作正在调用redirectotoaction,则会出现以下错误。

InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

TempData使用Session,后者本身使用IDistributedCacheIDistributedCache没有能力接受对象或序列化对象。结果,您需要自己执行此操作,即:

TempData["PopupMessages"] = JsonConvert.SerializeObject(_popupMessages);

然后,当然,在重定向之后,您需要将其反序列化为所需的对象:

ViewData["PopupMessages"] = JsonConvert.DeserializeObject<List<PopupMessage>>(TempData["PopupMessages"]);

答案 1 :(得分:0)

发生这种类型错误的另一种情况是从AspNetCore 2.2升级到3.0-并且我将AzureAD作为OpenID Connect提供程序-当它尝试处理AzureAD cookie时,它抛出了TempDataProvider和抱怨它无法序列化Int64类型。此问题已解决:

    services.AddMvc()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

答案 2 :(得分:0)

我试图将Exception对象序列化为TempData,最终不得不创建自己的TempDataSerializer使其正常工作(我正在将一些现有代码迁移到Core)。

// Startup.cs
services.AddSingleton<TempDataSerializer, JsonTempDataSerializer>();

// JsonTempDataSerializer.cs
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

public class JsonTempDataSerializer : TempDataSerializer
{
    private readonly JsonSerializer _jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All, // This may have security implications
    });

    public override byte[] Serialize(IDictionary<string, object>? values)
    {
        var hasValues = values?.Count > 0;
        if (!hasValues)
            return Array.Empty<byte>();

        using var memoryStream = new MemoryStream();
        using var writer = new BsonDataWriter(memoryStream);

        _jsonSerializer.Serialize(writer, values);

        return memoryStream.ToArray();
    }

    public override IDictionary<string, object> Deserialize(byte[] unprotectedData)
    {
        using var memoryStream = new MemoryStream(unprotectedData);
        using var reader = new BsonDataReader(memoryStream);

        var tempDataDictionary = _jsonSerializer.Deserialize<Dictionary<string, object>>(reader)
            ?? new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

        return tempDataDictionary;
    }
};