Reading Cookies in a Class Library RRS feed

  • Question

  • User744466301 posted
    I'm trying to retrieve a value from a cookie for a class that is included in a Class Library I have on VS.Net. However, it seems like I don't have access to Request.Cookies from a class library. I get the error "The type or namespace name 'Request' could not be found..." when I compile it in VS.Net. Is there any workaround on this?
    Saturday, March 12, 2005 2:04 PM

All replies

  • User-1069184416 posted
    Could you please check this article: Basics of Cookies regards
    Saturday, March 12, 2005 6:02 PM
  • User-170539329 posted

    The link seems to be broken. I'm looking for the same thing too :(

    Wednesday, February 11, 2009 5:14 AM
  • User-690506545 posted

    You'll need to add a reference to System.Web.

    Then you'll need to use the current HttpContext to get at the cookies.



    This is BAD, very BAD, BAD^100, BAD++, BAD#

    A class should have NO knowledge of cookies, or know anything about them, unless it's a specific cookie handler, and even then it should NEVER EVER have to access the HttpContext in that way.

    If your class has to deal with cookies, then consider passing in the VALUE of the cookie, rather than the cookie itself.

    For more on this, do some googling for "dependency injection".

    Wednesday, February 11, 2009 5:37 AM
  • User907845985 posted

    @Mr^B It's helpful if you explain why it's bad to help educate us on the issues that can arise if you did access cookies from a library class.

    I can understand that if it's used to configure service behaviour then this creates a dependency on cookies making it harder to store configuration in a different location if needed later. So it's better to decouple.

    However, in our case we're building a service to retrieve configuration and implementation supports reading from cookies. This seems a legitimate scenario for a class in a library to know about cookies, because the users of the library are free to build their own implementation that retrieves configuration from a different source and then configure dependency injection to use that instead.

    Wednesday, December 19, 2018 3:24 AM
  • User-943250815 posted

    If using HttpWebRequest, you have to initialize CookieContainer before call HttpWebResponse. If you don´t do that, HttpWebResponse.Cookies = nothing

    Dim URL = "http://www.whatever.com"
    Dim HttpReq As HttpWebRequest = CType(WebRequest.Create(pURL), HttpWebRequest)
    HttpReq.CookieContainer = New CookieContainer 
    Dim HttpRes As HttpWebResponse = CType(HttpReq.GetResponse, HttpWebResponse)

    Thursday, December 20, 2018 7:54 PM