views:

99

answers:

3

I have a CurrentUser class with a static property whose value was stored in a cookie last time the user visited the website. I would like to be able to read the value of the cookie from this class. Is it possible? It looks like Request.Cookies is only available in web pages. A simplified version of what I'm trying to do is:

class CurrentUser
{
public static string MyField
            {

                get
                {
                    return Request.Cookies["MyField"];
                }

            }

}

This doesn't work. I get this error message: "the name 'Request' does not exist in the current context'.

+4  A: 

Take a look at HttpContext.Current. It gives you access to Session, Response, Request, etc...

Bomlin
A: 

You could use HttpContext.Current.Request.Cookies["MyField"].. but I would strongly recommend against it, because you're not going to be able to test that.

In case a code context is the only solution for your CurrentUser problem, I would recommend using CodeContext directly instead of HttpContext, altough some machinery will be needed.

Can you explain why you don't recommend HttpContext

Well I suppose CurrentUser should be business code. And you would have a dependency on ASP.net's lifecycle if you use HttpContext. If you have to unit-test some business functionality relying on CurrentUser, you would have to go the whole path of an http request.

Vlagged
Can you explain why you don't recommend HttpContext.Current.Request.Cookies["MyField"]?
Anthony
+4  A: 
using System.Web;
...
return HttpContext.Current.Request.Cookies["MyField"];
wefwfwefwe