tags:

views:

53

answers:

3

I want to take HttpContext.Current.Request and HttpContext.Current.Session and wrap them together into one class.

Basically i want to write col["key"]; and have it check one of these for the key and if it doesnt exist to check the other.

AFAIK they don't share an interface (i looked around using "Go To Definition" but i am pretty bad). How would i write a class that can take both these types as parameters? I tried writing an interface but that didnt work because the classes dont inherit from them. The i tried assigning object o = request; then writing object o2 = o["key"]; but that also caused a compile error.

I am positive this can be done easily but i have no idea how.

+2  A: 
public class RequestOrSession
{
    public object this[string key]
    {
        get
        {
            HttpContext context = HttpContext.Current;
            if (context == null)
            {
                throw new InvalidOperationException("Where's the HttpContext?");
            }

            // if the same key exists in Request and Session
            // then Request will currently be given priority
            return context.Request[key] ?? context.Session[key];
        }
    }
}
LukeH
Would downvoters care to leave a comment? Isn't this exactly what the OP asked for?
LukeH
They're just jealous. :)
Groo
+4  A: 

How about extension method? E.g.:

public static object Get(this HttpContext context, string key)
{
    return context.Request[key] ?? context.Session[key];
}

Now you can use it like this

HttpContext.Current.Get(key);
Buu Nguyen
Nice solution. I would probably try to think of a better method name than Get though!
RichardOD
+2  A: 

HttpRequest has an indexer that does this, but not for session- it is slow though (code from reflector):

public string this[string key]
{
    get
    {
        string str = this.QueryString[key];
        if (str != null)
        {
            return str;
        }
        str = this.Form[key];
        if (str != null)
        {
            return str;
        }
        HttpCookie cookie = this.Cookies[key];
        if (cookie != null)
        {
            return cookie.Value;
        }
        str = this.ServerVariables[key];
        if (str != null)
        {
            return str;
        }
        return null;
    }
}

This isn't really an answer, just an observation. As it includes a code sample, I didn't put it as a comment.

RichardOD