Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

.net - 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 something
    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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...