6

我有一个函数可以检查 cookie(按名称)是否存在:

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

我有一个以特定于应用程序的方式处理 cookie 的类,我想将所有与 cookie 相关的函数合并到这个类中。但是,如果我只是将它从 aspx 页面(它当前所在的位置)移动到上述类,我将无法使用此代码,因为我收到错误:'Name' Response is not declared. 我修改了类以允许传递对Response对象的引用:

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

我的问题是:有没有更好的方法?

4

2 回答 2

13
HttpContext.Current.Response
HttpContext.Current.Request
于 2008-11-11T19:19:52.500 回答
2

HttpContext.Current 使用 Ambient Context 设计模式,因此您应该能够从代码中的任何位置访问 Response 对象。这是非常有用的。

对于那些想知道的人来说,环境上下文模式非常酷,这里有详细说明:

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

于 2008-11-11T19:22:57.160 回答