在静态类中包装会话处理

时间:2009-06-08 18:37:41

标签: c# session httpcontext static-classes

我将所有直接会话交互分离到一个单独的类中并使其成为静态,因为我不想多次创建新对象。但是,我希望确保没有并发问题或其他不可思议的事情。

以下是代码:

public static class HttpHelper
{

    public static string Get(string key)
    {
        object value = HttpContext.Current.Request.QueryString[key];
        return (value == null) ? null : value.ToString();
    }


    public static string Post(string key)
    {
        object value = HttpContext.Current.Request.Form[key];
        return (value == null) ? null : value.ToString();
    }

    public static string Session(string key)
    {
        object value = HttpContext.Current.Session[key];
        return (value == null) ? null : value.ToString();
    }

    public static void ClearSession(string key)
    {
        HttpContext.Current.Session[key] = null;
    }

    public static void StoreInSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

}

4 个答案:

答案 0 :(得分:1)

如果这有任何功能问题,许多应用程序很久以前就会失败:)

但是,我会指出这个模型对单元测试不是很好。您可能需要考虑使方法实例成员并将Session提供程序传递到此HttpHelper对象的构造函数中。

答案 1 :(得分:1)

以下是可能对您有所帮助的类似问题的答案 - 它可以让您避免使用密钥完全访问会话值并为您提供类型安全的属性:

How to access session variables from any class in ASP.NET?

答案 2 :(得分:0)

从概念上讲,你应该没事。即使在你可能期望竞争条件的部分回发(EG,AJAX)场景中,你应该没问题。会话状态使用reader/writer lock来保证您的安全。

我倾向于在我的项目中做类似的事情,尽管我喜欢将实际有效的会话条目(键等)封装到属性中。我发现它可以使应用程序代码更加一致,而且 - 更重要的是 - 消除了魔术键字符串拼写错误的可能性,这会使应用程序以极其意想不到的方式运行。

如果您为应用状态执行类似操作,则必须确保在设置之前锁定和解锁值。

答案 3 :(得分:0)

我不确定这个包装器是否有用,但我认为你可以做以下改进 而不是

public static string Get(string key)
{
    object value = HttpContext.Current.Request.QueryString[key];
    return (value == null) ? null : value.ToString();
}

你可以使用

public static string Get(string key)
{
    return HttpContext.Current.Request.QueryString[key];
}

Post方法相同。 如果您可以通过StoreInSession方法在会话中存储任何对象,那么您的Session方法是否只返回字符串是真的吗?

相关问题