Enables ASP.NET to read the HTTP values sent by a client during a Web request.
public ref class HttpRequest sealed
public sealed class HttpRequest
type HttpRequest = class
Public NotInheritable Class HttpRequest
The following examples access the HttpRequest instance for the current request by using the Request property of the Page class.
You can use simplified syntax for accessing data from the QueryString, Form, Cookies, or ServerVariables collections. You can write Request["key"]
.
The first example shows how to retrieve a query string value when loading a page.
public partial class AddToCart : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string rawId = Request["ProductID"];
int productId;
if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
usersShoppingCart.AddToCart(productId);
}
}
else
{
throw new Exception("Tried to call AddToCart.aspx without setting a ProductId.");
}
Response.Redirect("ShoppingCart.aspx");
}
}
Public Class AddToCart
Inherits Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim rawId = Request("ProductID")
Dim productId As Integer
If Not String.IsNullOrEmpty(rawId) And Integer.TryParse(rawId, productId) Then
Using usersShoppingCart As New ShoppingCartActions()
usersShoppingCart.AddToCart(productId)
End Using
Else
Throw New Exception("Tried to call AddToCart.aspx without setting a ProductId.")
End If
Response.Redirect("ShoppingCart.aspx")
End Sub
End Class
The next example shows how to check if the request is authenticated and retrieve the raw URL.
public partial class RestrictedPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
var rawUrl = Request.RawUrl;
Response.Redirect("/Account/Login?ru=" + Server.HtmlEncode(rawUrl));
}
}
}
Public Class RestrictedPage
Inherits Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Request.IsAuthenticated Then
Dim rawUrl = Request.RawUrl
Response.Redirect("/Account/Login?ru=" + Server.HtmlEncode(rawUrl))
End If
End Sub
End Class
This example uses the StreamWriter class to write the values of several HttpRequest class properties to a file. For properties that are of type string, the values are HTML encoded as they are written to the file. Properties that represent a collection are looped through, and each key/value pair that they contain is written to the file.
Important
This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.
<%@ Page Language="C#" %>
<%@ import Namespace="System.Threading" %>
<%@ import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
/* NOTE: To use this sample, create a c:\temp\CS folder,
* add the ASP.NET account (in IIS 5.x <machinename>\ASPNET,
* in IIS 6.x NETWORK SERVICE), and give it write permissions
* to the folder.*/
private const string INFO_DIR = @"c:\temp\CS\RequestDetails";
public static int requestCount;
private void Page_Load(object sender, System.EventArgs e)
{
// Create a variable to use when iterating
// through the UserLanguages property.
int langCount;
int requestNumber = Interlocked.Increment(ref requestCount);
// Create the file to contain information about the request.
string strFilePath = INFO_DIR + requestNumber.ToString() + @".txt";
StreamWriter sw = File.CreateText(strFilePath);
try
{
// <snippet2>
// Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(DateTime.Now.ToString()));
sw.WriteLine(Server.HtmlEncode(Request.CurrentExecutionFilePath));
sw.WriteLine(Server.HtmlEncode(Request.ApplicationPath));
sw.WriteLine(Server.HtmlEncode(Request.FilePath));
sw.WriteLine(Server.HtmlEncode(Request.Path));
// </snippet2>
// <snippet3>
// Iterate through the Form collection and write
// the values to the file with HTML encoding.
// String[] formArray = Request.Form.AllKeys;
foreach (string s in Request.Form)
{
sw.WriteLine("Form: " + Server.HtmlEncode(s));
}
// </snippet3>
// <snippet4>
// Write the PathInfo property value
// or a string if it is empty.
if (Request.PathInfo == String.Empty)
{
sw.WriteLine("The PathInfo property contains no information.");
}
else
{
sw.WriteLine(Server.HtmlEncode(Request.PathInfo));
}
// </snippet4>
// <snippet5>
// Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.PhysicalApplicationPath));
sw.WriteLine(Server.HtmlEncode(Request.PhysicalPath));
sw.WriteLine(Server.HtmlEncode(Request.RawUrl));
// </snippet5>
// <snippet6>
// Write a message to the file dependent upon
// the value of the TotalBytes property.
if (Request.TotalBytes > 1000)
{
sw.WriteLine("The request is 1KB or greater");
}
else
{
sw.WriteLine("The request is less than 1KB");
}
// </snippet6>
// <snippet7>
// Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.RequestType));
sw.WriteLine(Server.HtmlEncode(Request.UserHostAddress));
sw.WriteLine(Server.HtmlEncode(Request.UserHostName));
sw.WriteLine(Server.HtmlEncode(Request.HttpMethod));
// </snippet7>
// <snippet8>
// Iterate through the UserLanguages collection and
// write its HTML encoded values to the file.
for (langCount=0; langCount < Request.UserLanguages.Length; langCount++)
{
sw.WriteLine(@"User Language " + langCount +": " + Server.HtmlEncode(Request.UserLanguages[langCount]));
}
// </snippet8>
}
finally
{
// Close the stream to the file.
sw.Close();
}
lblInfoSent.Text = "Information about this request has been sent to a file.";
}
private void btnSendInfo_Click(object sender, System.EventArgs e)
{
lblInfoSent.Text = "Hello, " + Server.HtmlEncode(txtBoxName.Text) +
". You have created a new request info file.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<p>
</p>
<p>
Enter your name here:
<asp:TextBox id="txtBoxName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button id="btnSendInfo" onclick="btnSendInfo_Click" runat="server" Text="Click Here"></asp:Button>
</p>
<p>
<asp:Label id="lblInfoSent" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ import Namespace="System.Threading" %>
<%@ import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' NOTE: To use this sample, create a c:\temp\CS folder,
' add the ASP.NET account (in IIS 5.x <machinename>\ASPNET,
' in IIS 6.x NETWORK SERVICE), and give it write permissions
' to the folder.
Private Const INFO_DIR As String = "c:\temp\VB\RequestDetails"
Public Shared requestCount As Integer
Private Sub Page_Load(sender As Object, e As System.EventArgs)
' Create a variable to use when iterating
' through the UserLanguages property.
Dim langCount As Integer
' Create a counter to name the file.
Dim requestNumber As Integer = _
Interlocked.Increment(requestCount)
' Create the file to contain information about the request.
Dim strFilePath As String = INFO_DIR & requestNumber.ToString() & ".txt"
Dim sw As StreamWriter = File.CreateText(strFilePath)
Try
' <snippet2>
' Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(DateTime.Now.ToString()))
sw.WriteLine(Server.HtmlEncode(Request.CurrentExecutionFilePath))
sw.WriteLine(Server.HtmlEncode(Request.ApplicationPath))
sw.WriteLine(Server.HtmlEncode(Request.FilePath))
sw.WriteLine(Server.HtmlEncode(Request.Path))
' </snippet2>
' <snippet3>
' Iterate through the Form collection and write
' the values to the file with HTML encoding.
For Each s As String In Request.Form
sw.WriteLine("Form: " & Server.HtmlEncode(s))
Next s
' </snippet3>
' <snippet4>
' Write the PathInfo property value
' or a string if it is empty.
If Request.PathInfo = String.Empty Then
sw.WriteLine("The PathInfo property contains no information.")
Else
sw.WriteLine(Server.HtmlEncode(Request.PathInfo))
End If
' </snippet4>
' <snippet5>
' Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.PhysicalApplicationPath))
sw.WriteLine(Server.HtmlEncode(Request.PhysicalPath))
sw.WriteLine(Server.HtmlEncode(Request.RawUrl))
' </snippet5>
' <snippet6>
' Write a message to the file dependent upon
' the value of the TotalBytes property.
If Request.TotalBytes > 1000 Then
sw.WriteLine("The request is 1KB or greater")
Else
sw.WriteLine("The request is less than 1KB")
End If
' </snippet6>
' <snippet7>
' Write request information to the file with HTML encoding.
sw.WriteLine(Server.HtmlEncode(Request.RequestType))
sw.WriteLine(Server.HtmlEncode(Request.UserHostAddress))
sw.WriteLine(Server.HtmlEncode(Request.UserHostName))
sw.WriteLine(Server.HtmlEncode(Request.HttpMethod))
' </snippet7>
' <snippet8>
' Iterate through the UserLanguages collection and
' write its HTML encoded values to the file.
For langCount = 0 To Request.UserLanguages.Length - 1
sw.WriteLine("User Language " & langCount.ToString() & _
": " & Server.HtmlEncode( _
Request.UserLanguages(langCount)))
Next
' </snippet8>
Finally
' Close the stream to the file.
sw.Close()
End Try
lblInfoSent.Text = _
"Information about this request has been sent to a file."
End Sub 'Page_Load
Private Sub btnSendInfo_Click(sender As Object, e As System.EventArgs)
lblInfoSent.Text = _
"Hello, " & Server.HtmlEncode(txtBoxName.Text) & _
". You have created a new request info file."
End Sub 'btnSendInfo_Click
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<p>
</p>
<p>
Enter your name here:
<asp:TextBox id="txtBoxName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button id="btnSendInfo" onclick="btnSendInfo_Click" runat="server" Text="Click Here"></asp:Button>
</p>
<p>
<asp:Label id="lblInfoSent" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
The methods and properties of the HttpRequest class are exposed through the Request
properties of the HttpApplication, HttpContext, Page, and UserControl classes.
To access data from the QueryString, Form, Cookies, or ServerVariables collections, you can write Request["key"]
, as shown in the example for the QueryString property.
Note
Unicode support for HttpRequest class members requires IIS version 6.0 or later.
Constructors Properties AcceptTypesGets a string array of client-supported MIME accept types.
AnonymousIDGets the anonymous identifier for the user, if present.
ApplicationPathGets the ASP.NET application's virtual application root path on the server.
AppRelativeCurrentExecutionFilePathGets the virtual path of the application root and makes it relative by using the tilde (~) notation for the application root (as in "~/page.aspx").
BrowserGets or sets information about the requesting client's browser capabilities.
ClientCertificateGets the current request's client security certificate.
ContentEncodingGets or sets the character set of the entity-body.
ContentLengthSpecifies the length, in bytes, of content sent by the client.
ContentTypeGets or sets the MIME content type of the incoming request.
CookiesGets a collection of cookies sent by the client.
CurrentExecutionFilePathGets the virtual path of the current request.
CurrentExecutionFilePathExtensionGets the extension of the file name that is specified in the CurrentExecutionFilePath property.
FilePathGets the virtual path of the current request.
FilesGets the collection of files uploaded by the client, in multipart MIME format.
FilterGets or sets the filter to use when reading the current input stream.
FormGets a collection of form variables.
HeadersGets a collection of HTTP headers.
HttpChannelBindingGets the ChannelBinding object of the current HttpWorkerRequest instance.
HttpMethodGets the HTTP data transfer method (such as GET
, POST
, or HEAD
) used by the client.
Gets the contents of the incoming HTTP entity body.
IsAuthenticatedGets a value indicating whether the request has been authenticated.
IsLocalGets a value indicating whether the request is from the local computer.
IsSecureConnectionGets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).
Item[String]Gets the specified object from the QueryString, Form, Cookies, or ServerVariables collections.
LogonUserIdentityGets the WindowsIdentity type for the current user.
ParamsGets a combined collection of QueryString, Form, Cookies, and ServerVariables items.
PathGets the virtual path of the current request.
PathInfoGets the additional path information for a resource with a URL extension.
PhysicalApplicationPathGets the physical file system path of the currently executing server application's root directory.
PhysicalPathGets the physical file system path corresponding to the requested URL.
QueryStringGets the collection of HTTP query string variables.
RawUrlGets the raw URL of the current request.
ReadEntityBodyModeGets a value that indicates whether the request entity body has been read, and if so, how it was read.
RequestContextGets the RequestContext instance of the current request.
RequestTypeGets or sets the HTTP data transfer method (GET
or POST
) used by the client.
Gets a collection of Web server variables.
TimedOutTokenGets a CancellationToken object that is tripped when a request times out.
TlsTokenBindingInfoGets the TLS token binding information. The property enables applications to retrieve token information from incoming HTTP requests for enhanced authentication.
TotalBytesGets the number of bytes in the current input stream.
UnvalidatedGets the HTTP request values without triggering request validation.
UrlGets information about the URL of the current request.
UrlReferrerGets information about the URL of the client's previous request that linked to the current URL.
UserAgentGets the raw user agent string of the client browser that has been provided. Please note it may be null.
UserHostAddressGets the IP host address of the remote client.
UserHostNameGets the DNS name of the remote client.
UserLanguagesGets a sorted string array of client language preferences.
MethodsRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4