【问题标题】:Access Response Object in a class ASP.NET访问 ASP.NET 类中的响应对象
【发布时间】:2019-10-11 10:51:18
【问题描述】:

我有一个函数可以检查 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

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

【问题讨论】:

    标签: asp.net class cookies httpresponse


    【解决方案1】:
    HttpContext.Current.Response
    HttpContext.Current.Request
    

    【讨论】:

    • 将 Request 和 Response 对象作为参数传递给函数有什么问题?
    • @palswim 如果你想function myFunc(response As System.Web.HttpResponse) 为我工作。 Intellisense 建议使用 system.net.httpresponse,但使用 .Web 有效
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多