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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Well:
HttpContext.Currentis a static property returning the currentHttpContextfor the threadHttpContext.Requestis an instance property returning theHttpRequestfor theHttpContextyou call it onPage.Requestis an instance property inPage, returning theRequestassociated with the page you call it on (typically implicitlythis)
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.
Method 2
They are all the same. There are simply various shortcuts built-into classes you’re inheriting from such as Controller and Page.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0