Asp.net is it possible to read cookie value from static class?

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

class CurrentUser
{
public static string MyField
            {

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

            }

}

      

This does not work. I am getting this error message: "the name 'query' does not exist in the current context".

+2


source to share


3 answers


using System.Web;
...
return HttpContext.Current.Request.Cookies["MyField"];

      



+9


source


Take a look at HttpContext.Current. This gives you access to session, responses, requests, etc.



+4


source


You can use HttpContext.Current.Request.Cookies["MyField"]

.. but I would highly recommend against it because you won't be able to test it.

If the code context is the only solution for your CurrentUser problem, then I would recommend using CodeContext directly instead of HttpContext, although some machines will be needed.

Can you explain why you don't recommend HttpContext

Well, I suppose CurrentUser should be business code. And you will have ASP.net lifecycle dependency if you are using HttpContext. If you need to perform a single check on some business functions that rely on CurrentUser, you have to go all the way through the http request.

0


source







All Articles