0

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

这是代码:

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

4 回答 4

1

If there were any functional problems with this, many applications would have failed long ago :)

However, I would point out that this model is not very good for unit testing. You might want to consider making the methods instance members and passing a Session provider into the constructor of this HttpHelper object.

于 2009-06-08T18:41:38.653 回答
1

Here's an answer from a similar question that may help you - it will enable you to avoid using keys to access the session values altogether and give you type-safe properties:

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

于 2009-06-08T18:43:37.853 回答
0

Conceptually, you should be fine. Even in a partial-postback (EG, AJAX) scenario where you might expect race conditions, you should be OK. Session state uses a reader/writer lock to keep you safe.

I tend to do something similar in my projects, though I'm a fan of encapsulating out the actual valid session entries (keys, etc.) into properties. I find it keeps the app code more consistent, and -- more importantly -- removes the possibility of a typo on a magic key string that would make the app behave in wildly unexpected ways.

If you do something similar for app state, then you do have to make sure you lock and unlock values before setting them.

于 2009-06-08T18:46:27.723 回答
0

I am not sure is this wrapper usefull,but I think you could do the following improvements Instead of

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

you can use

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

The same for Post method. And is it true that your Session method returns only string , if you can store any object in session by StoreInSession method?

于 2009-06-08T18:51:03.050 回答