开发者

Difference between HttpContext.Request and Request

What is the difference between the three ASP.NET objects:

  • HttpContext.Current.Request
  • HttpContext.Request
  • Request

Are these exactly the same?

Edit 1

Do these objects behave differently inside global.asax/global.asax.vb and default.aspx/default.aspx.vb.

Edit 2

OK I'll try to be specific this time. Which of the following should I use:

' File: global.asax
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)
    If Request.Url.Port = 80 Then
    'If HttpContext.Current.Request.Url.Port = 80 Then
    'If HttpContext.Request.Url.Port = 80 Then
        'do som开发者_如何学Cething
    End If
End Sub

' File: default.aspx
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    If Request.Url.Port = 80 Then
    'If HttpContext.Current.Request.Url.Port = 80 Then
    'If HttpContext.Request.Url.Port = 80 Then
        'do something
    End If
End Sub


Well:

  • HttpContext.Current is a static property returning the current HttpContext for the thread
  • HttpContext.Request is an instance property returning the HttpRequest for the HttpContext you call it on
  • Page.Request is an instance property in Page, returning the Request associated with the page you call it on (typically implicitly this)

So HttpContext.Current.Request will use both of the first two properties in order to get the request associated with the current thread. If you're in the thread dealing with a request, that's going to be the same as the Page.Request within the relevant page which is being rendered.

However, if your rendering kicks off a different thread, the code running in the other thread can still get at the Request via Page.Request (because it's just a normal property) but there'll be no HttpContext associated with the thread - so HttpContext.Current.Request wouldn't work.

EDIT: To respond to the edited question, in global.asax the Request property refers to HttpApplication.Request, and is probably the best approach to use. HttpContext.Request won't work, because that's trying to access a static property as if it were an instance property. HttpContext.Current.Request should work, assuming the context has been associated with the thread by that point.


They are all the same. There are simply various shortcuts built-into classes you're inheriting from such as Controller and Page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜