使用一般静态方法进行会话缓存

时间:2019-04-25 15:18:06

标签: c# asp.net

我正在开发Web应用程序以向用户显示信用卡信息。我从不同的Web服务获取卡信息,正在创建多个对象来存储这些值。我打算按卡号和函数名(在常量值中区分对象,例如ccInfo是cardInformationObject的函数名)在会话中存储对象。

我创建了一个通用静态类来实现相同目的,但是由于我有多种类型的对象而无法正常工作,并且C#不允许将对象类型转换为通用类型。请参见下面的代码段。

// Generic static class
  public class SessionCache<T>
  {
    public static T Add(string cardNumber, string functionName, T data)
    {
        var sessionKey = "${cardNumber}_{functionName}";
        if(HttpContext.Current != null && HttpContext.Current.Session != null)
        {
          HttpContext.Current.Session[sessionKey] = data;
        }
     }     

      public static T Get(string cardNumber, string functionName)
      {
        var sessionKey = "${cardNumber}_{functionName}";
        if(HttpContext.Current != null && HttpContext.Current.Session != null)
        {
          return HttpContext.Current.Session[sessionKey] as T; // This line throw errors because i am type casting to generic type
        }
      }     
   }

现在我有两个选择:

  • 创建抽象类/接口,从中继承所有不同的响应对象。用抽象类/接口替换通用T。
  • 创建哈希表,在哈希表中添加不同的对象。将字典存储在会话中。
  • 哪个会是更好的选择?还有其他方法吗?

    2 个答案:

    答案 0 :(得分:1)

    您不能在此行中从通用类型键入强制类型转换

    return HttpContext.Current.Session[sessionKey] as T;
    

    因为as运算符可能返回null,并且您的泛型类型可能是不可为null的类型,例如,您可以将其称为SessionCache<int>

    您可以在通用类上定义约束:

    public class SessionCache<T> where T : class
    

    或者,您可以对return语句使用强制转换:

    return (T)HttpContext.Current.Session[sessionKey];
    

    请记住,后面的解决方案可能会在运行时抛出InvalidCastException

    答案 1 :(得分:0)

    我喜欢使用像这样的强类型包装器:

    public static class SN
    {
        private static string CardNumber
        {
            get => (string)HttpContext.Current.Session["CardNumber"];
            set => HttpContext.Current.Session["CardNumber"] = value;
        }
    }
    

    请记住,该会话仅适用于存储有关当前用户的数据。要存储应用程序范围的数据,请使用HttpContext.Current.ApplicationHttpContext.Current.Cache

    相关问题