Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Response Object in a class ASP.NET

I have a function that checks if a cookie (by name) exists or not:

Private Function cookieExists(ByVal cName As String) As Boolean
    For Each c As HttpCookie In Response.Cookies
        If c.Name = cName Then Return True
    Next
    Return False
End Function

I have a class that handles cookies in an application-specific manner, and I want to consolidate all the cookie-related functions to this class. However, I cannot use this code if I simply move it from the aspx page (where it currently resides) to the aforementioned class because I get the error: 'Name' Response is not declared. I modified the class to allow the passing of a reference to the Response object:

Public Function cookieExists(ByVal cName As String, ByRef Response As HttpResponse) As Boolean
    For Each c As HttpCookie In Response.Cookies
        If c.Name = cName Then Return True
    Next
    Return False
End Function

My question is: Is there a better way?

like image 876
Anders Avatar asked Nov 11 '08 19:11

Anders


2 Answers

HttpContext.Current.Response
HttpContext.Current.Request
like image 69
Gordon Bell Avatar answered Sep 28 '22 16:09

Gordon Bell


HttpContext.Current uses the Ambient Context design pattern, so you should be able to access the Response object from just about anywhere in your code. It is very useful.

For those wondering, the Ambient Context pattern is very cool, and is detailed here:

http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/

like image 30
FlySwat Avatar answered Sep 28 '22 18:09

FlySwat