同时使用Microsoft.Web.RedisSessionStateProvider和Microsoft.Web.RedisOutputCacheProvider

时间:2018-06-02 06:55:56

标签: serialization session-state outputcache redis-cache

我已经安装并使用了Microsoft.Web.RedisSessionStateProvider一段时间,在查看OutputCaching之后我还考虑安装了Microsoft.Web.RedisOutputCacheProvider,但是它们都有Microsoft.Web.Redis.ISerializer接口,它打破了我的JsonCacheSerializer,因为它使用ISerializer接口。

我在VS 2017中收到错误,其中包含......

类型'ISerializer'存在于Microsoft.Web.RedisOutputCacheProvider和Microsoft.Web.RedisSessionStateProvider

我用于SessionState的JsonCacheSerializer代码是:

public class JsonCacheSerializer : Microsoft.Web.Redis.ISerializer
{
    private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings()
    {
        TypeNameHandling = TypeNameHandling.All,
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
        PreserveReferencesHandling = PreserveReferencesHandling.Objects,
        Error = (serializer, err) => {
            err.ErrorContext.Handled = true;
        }
    };

    public byte[] Serialize(object data)
    {
        return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, Settings));
    }

    public object Deserialize(byte[] data)
    {
        return data == null ? null : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), Settings);
    }
}

这是否意味着必须使用其中一种,而不是两种?

1 个答案:

答案 0 :(得分:0)

您可以使用C#的外部别名功能 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias

Visual Studio示例: 1)右键单击Microsoft.Web.RedisOutputCacheProvider,然后将以下内容放入“别名”字段:

global,redisoutputcacheprovider

2)右键单击Microsoft.Web.RedisSessionStateProvider,然后将以下内容放入“别名”字段:

global,redissessionstateprovider

然后在代码文件顶部添加:

extern alias redissessionstateprovider;
extern alias redisoutputcacheprovider;

最后将您的课程声明为:

public class JsonCacheSessionStateSerializer : redissessionstateprovider::Microsoft.Web.Redis.ISerializer