The Page Class
The Page Class
Every web page is a custom class that inherits from the System.
Web. UI. Page control.
The Page class in ASP.NET is the base class for all webpages in a web
application.
It provides properties, methods, and events to manage the webpage's
lifecycle, handle user interactions, and control the rendering of the
page.
The Page class allows developers to access request and response data,
manage user sessions, and interact with server-side controls.
It simplifies tasks such as form submission, user authentication, and
dynamic content generation.
The Page class ensures that webpages are processed on the server
and delivered to the client's browser efficiently.
Sets or gets
the title of
the webpage.
This appears
Title Page.Title = "My Cool Game Page";
in the
browser's
title bar or
tab.
Checks if the
page is being
loaded in
if (!Page.IsPostBack) { /* Do something on first load
IsPostBack response to a
*/ }
postback (like
a form
submission).
Provides
information
about the
current web
Request string userName = Page.Request.QueryString["name"];
request, such
as query
strings or
form data.
and is used
to send
output to the
client.
Manages
user-specific
data that
persists
Session across Page.Session["user"] = "JohnDoe";
multiple
pages (like a
shopping
cart).
Allows storing
and
retrieving
Cache Page.Cache["time"] = DateTime.Now;
data that can
be reused for
faster access.
Provides a
collection of
Controls all the Control myButton = Page.Controls[0];
controls on
the page.
Used to
register and
emit client-
Page.ClientScript.RegisterStartupScript(this.GetType(),
ClientScript side scripts
"alert", "alert('Hello!');", true);
(JavaScript)
to the
webpage.
Determines
whether the
page
EnableViewStat
maintains its Page.EnableViewState = true;
e
state (data)
across
postbacks.
server-side
operations
and
information.
Represents
the currently
authenticate
d user,
User providing string userName = Page.User.Identity.Name;
information
about the
user’s
identity.
Quick Breakdown
1. Title: Sets the text that appears in the browser tab.
o Example: Page.Title = "My Cool Game Page";
o What It Does: Sets the tab title to "My Cool Game Page".
2. IsPostBack: Checks if the page is reloaded due to a user action like
clicking a button.
o Example: if (!Page.IsPostBack) { /* Do something on first load */
}
o What It Does: Runs code only the first time the page loads.
3. Request: Gets information sent to the page, like form data.
o Example: string userName =
Page.Request.QueryString["name"];
o What It Does: Gets the value of the query string parameter
"name".
4. Response: Sends information back to the user's browser.
o Example: Page.Response.Write("Hello, World!");
o What It Does: Displays "Hello, World!" on the webpage.
5. Session: Stores user-specific information for use across different
pages.
o Example: Page.Session["user"] = "JohnDoe";
o What It Does: Saves the user name "JohnDoe" in the session.
6. Cache: Stores data to make future requests faster.
o Example: Page.Cache["time"] = DateTime.Now;
o What It Does: Saves the current time in the cache.
7. Controls: Lists all the elements (like buttons and text boxes) on the
page.
o Example: Control myButton = Page.Controls[0];
o What It Does: Gets the first control on the page.
8. ClientScript: Adds JavaScript code to the page.
o Example:
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('Hello!');", true);
o What It Does: Shows a pop-up alert saying "Hello!" when the
page loads.
9. EnableViewState: Determines if the page keeps its data between
postbacks.
o Example: Page.EnableViewState = true;
o What It Does: Keeps the page's data when you submit a form.
10. Server: Helps with server-side tasks like file paths and URL
encoding.
o Example: string serverPath = Page.Server.MapPath("~");
o What It Does: Gets the server path to the root of the
application.
11. User: Information about the logged-in user.
o Example: string userName = Page.User.Identity.Name;
o What It Does: Gets the name of the currently logged-in user.
Gets the
values of the
QueryString query string string id = Request.QueryString["id"];
parameters in
the URL.
Gets the
values
submitted in a
Form string name = Request.Form["name"];
form (like text
input or
selections).
Gets the
cookies sent
Cookies HttpCookie cookie = Request.Cookies["user"];
by the
browser.
Gets the IP
address of the
UserHostAddress string userIp = Request.UserHostAddress;
client (the
user's device).
Property Description Example
Determines
whether the
page
EnableViewState maintains its Page.EnableViewState = true;
state (data)
across
postbacks.
Provides
methods and
properties for
handling
Server string serverPath = Page.Server.MapPath("~");
server-side
operations
and
information.
Represents
the currently
authenticated
user,
User providing string userName = Page.User.Identity.Name;
information
about the
user’s
identity.
Gets the
virtual
ApplicationPath application string appPath = Request.ApplicationPath;
root path on
the server.
URL.
Checks if the
user has been
IsAuthenticated bool isAuthenticated = Request.IsAuthenticated;
authenticated
.
Checks if the
IsSecureConnectio request is
bool isSecure = Request.IsSecureConnection;
n being made
over HTTPS.
Gets a
collection of
variables string serverSoftware =
ServerVariables
provided by Request.ServerVariables["SERVER_SOFTWARE"];
the web
server.
Quick Breakdown
1. QueryString: Captures the information after the "?" in the URL.
o Example: If the URL is http://example.com/page?name=John,
you can get "John" with Request.QueryString["name"];
2. Form: Captures data submitted through a form on the webpage.
o Example: If a form has an input field named "name", you can
get its value with Request.Form["name"];
3. Cookies: Stores small pieces of data sent by the browser, like user
preferences.
o Example: If a cookie named "user" is set, you can get it with
Request.Cookies["user"];
4. Headers: Contains information about the client's request, like the
browser type.
o Example: You can get the browser information with
Request.Headers["User-Agent"];
5. HttpMethod: Tells you whether the request is a GET, POST, etc.
o Example: string method = Request.HttpMethod; might return
"GET" or "POST".
6. Url: The full address of the webpage being requested.
o Example: string currentUrl = Request.Url.ToString(); could be
http://example.com/page.
7. UrlReferrer: The address of the previous page that linked to the
current page.
o Example: string referrer = Request.UrlReferrer.ToString(); might
be http://example.com/home.
8. UserHostAddress: The IP address of the user making the request.
o Example: string userIp = Request.UserHostAddress; might
return something like 192.168.1.1.
9. UserHostName: The DNS name of the user making the request.
o Example: string userHostName = Request.UserHostName;
might return something like host.example.com.
10. Files: Manages file uploads from the client.
o Example: If a form has a file input named "fileUpload", you can
get the uploaded file with Request.Files["fileUpload"];
11. EnableViewState: Determines if the page keeps its data
between postbacks.
o Example: Page.EnableViewState = true;
o What It Does: Keeps the page's data when you submit a form.
12. Server: Helps with server-side tasks like file paths and URL
encoding.
o Example: string serverPath = Page.Server.MapPath("~");
o What It Does: Gets the server path to the root of the
application.
13. User: Information about the logged-in user.
o Example: string userName = Page.User.Identity.Name;
o What It Does: Gets the name of the currently logged-in user.
14. ApplicationPath: The virtual path of the application on the
server.
o Example: string appPath = Request.ApplicationPath;
o What It Does: Gets the root path of the application, like
/MyApp.
15. PhysicalPath: The physical file system path corresponding to
the requested URL.
o Example: string physPath = Request.PhysicalPath;
o What It Does: Gets the actual file path on the server, like C:\
Websites\MyApp\index.aspx.
16. IsAuthenticated: Checks if the user is logged in.
o Example: bool isAuthenticated = Request.IsAuthenticated;
o What It Does: Returns true if the user is authenticated, false
otherwise.
17. IsSecureConnection: Checks if the request is made over
HTTPS.
o Example: bool isSecure = Request.IsSecureConnection;
o What It Does: Returns true if the connection is secure (HTTPS),
false otherwise.
18. ServerVariables: A collection of server-specific variables.
o Example: string serverSoftware =
Request.ServerVariables["SERVER_SOFTWARE"];
o What It Does: Gets information like the web server software
being used.
These properties give you powerful ways to interact with and respond to the
requests made to your web application, making it easier to build dynamic
and responsive web pages.
How It Works
When someone visits your website, their browser sends a request to
your server. The HttpRequest class catches this request and lets you access
all the information it carries. This way, you can react to what the user wants
to do, like showing a specific webpage, processing form data, or customizing
the user experience based on their input.
In short, the HttpRequest class is your way of understanding and reacting to
what users are asking for when they interact with your website.
HttpResponse Class
The HttpResponse class in ASP.NET is like a mailbox that sends information
back to the user's browser after the server processes a request. This class
lets you control what gets sent back, such as the webpage content, cookies,
or special instructions for the browser.
HttpResponse Properties
Property/ Descriptio
Example
Method n
Enables or
disables
BufferOutput buffering of Response.BufferOutput = true;
the
response.
Manages
cache-
specific
headers to
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10
Cache control how
));
documents
are cached
on the
network.
Manages
cookies that
Cookies Response.Cookies["user"].Value = "JohnDoe";
are sent to
the client.
Writes a
string of
text directly
Write() to the Response.Write("Hello, World!");
response
output
stream.
Writes a
byte array
directly to
byte[] data = { 0x0, 0x1, 0x2 };
BinaryWrite() the
Response.BinaryWrite(data);
response
output
stream.
Writes the
content of a
file directly
WriteFile() to the Response.WriteFile("path/to/file.txt");
response
output
stream.
a different
URL.
Quick Breakdown
1. BufferOutput: Controls whether the response is buffered.
o Example: Response.BufferOutput = true;
o What It Does: Enables buffering so the content is sent only
after the response is fully ready.
2. Cache: Manages how the response is cached by the client and proxy
servers.
o Example:
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
o What It Does: Sets the expiration time for the cached response
to 10 minutes from now.
3. Cookies: Manages cookies to store small pieces of data on the client's
browser.
o Example: Response.Cookies["user"].Value = "JohnDoe";
o What It Does: Creates a cookie named "user" with the value
"JohnDoe".
4. Write(): Writes a string directly to the response output stream.
o Example: Response.Write("Hello, World!");
o What It Does: Displays "Hello, World!" on the webpage.
5. BinaryWrite(): Writes a binary data array directly to the response
output stream.
o Example: byte[] data = { 0x0, 0x1, 0x2 };
Response.BinaryWrite(data);
o What It Does: Sends binary data to the client.
6. WriteFile(): Writes the contents of a specified file directly to the
response.
o Example: Response.WriteFile("path/to/file.txt");
o What It Does: Sends the contents of "file.txt" to the client.
7. Redirect(): Redirects the user to a different URL.
o Example: Response.Redirect("http://example.com");
o What It Does: Redirects the user to "http://example.com".
How It Works
The HttpResponse class allows you to control what information gets sent
back to the user's browser. By using its properties and methods, you can:
BufferOutput: Decide if the response should be sent in chunks or all
at once.
Cache: Manage how the browser and proxies cache the response.
Cookies: Set cookies to store data on the client's machine.
Write(): Send plain text data.
BinaryWrite(): Send binary data.
WriteFile(): Send the content of a file.
Redirect(): Redirect the browser to a different URL.
This helps you create dynamic, responsive, and interactive web applications.
ServerUtility Class
The ServerUtility class, often accessed through the Server property of
a web page or application, provides various utility methods that help with
server-side processing. These methods assist with tasks such as URL
encoding, path mapping, and error handling.
ServerUtility Methods
Descri
Method Example
ption
Convert
sa
string
into a
HtmlEnc string encoded =
format
ode() Server.HtmlEncode("<script>alert('hi');</script>");
that is
safe for
use in
HTML.
HTML-
encode
d back
to its
original
form.
Convert
sa
string
into a
UrlEnco string encodedUrl = Server.UrlEncode("http://example.com?
format
de() name=John Doe");
that is
safe for
use in a
URL.
Convert
sa
URL-
string decodedUrl =
encode
UrlDeco Server.UrlDecode("http%3A%2F
d string
de() %2Fexample.com%3Fname
back to
%3DJohn+Doe");
its
original
form.
Convert
sa
virtual
(web)
MapPat path to
string physicalPath = Server.MapPath("/images/photo.jpg");
h() a
physica
l
(server)
path.
without
making
a
round-
trip
back to
the
client's
browser
.
Retriev
es the
last
error
GetLast
that Exception lastError = Server.GetLastError();
Error()
occurre
d on
the
server.
Clears
the
error
informa
ClearErr
tion for Server.ClearError();
or()
the
current
request
.
Instanti
ates a
COM
CreateO
object object comObject = Server.CreateObject("ProgID");
bject()
identifi
ed by a
ProgID.
Quick Breakdown
1. HtmlEncode(): Converts characters to HTML-safe characters.
o Example: string encoded =
Server.HtmlEncode("<script>alert('hi');</script>");
o What It Does: Converts < to <, > to >, and so on.
2. HtmlDecode(): Converts HTML-encoded characters back to their
original form.
o Example: string decoded =
Server.HtmlDecode("<script>alert('hi');</script>");
o What It Does: Converts < back to <, > back to >, etc.
3. UrlEncode(): Converts a string into a URL-friendly format.
o Example: string encodedUrl =
Server.UrlEncode("http://example.com?name=John Doe");
o What It Does: Converts spaces to + and special characters to
%xx format.
4. UrlDecode(): Converts a URL-encoded string back to its original form.
o Example: string decodedUrl = Server.UrlDecode("http%3A%2F
%2Fexample.com%3Fname%3DJohn+Doe");
o What It Does: Converts %xx format back to special characters.
5. MapPath(): Converts a web path to a physical file path on the server.
o Example: string physicalPath =
Server.MapPath("/images/photo.jpg");
o What It Does: Maps /images/photo.jpg to something like C:\
Websites\MyApp\images\photo.jpg.
6. Transfer(): Transfers execution to another page on the server without
a client round-trip.
o Example: Server.Transfer("AnotherPage.aspx");
o What It Does: Stops processing the current page and starts
processing "AnotherPage.aspx".
7. GetLastError(): Retrieves the last server error.
o Example: Exception lastError = Server.GetLastError();
o What It Does: Gets information about the most recent error
that occurred on the server.
8. ClearError(): Clears the current error information.
o Example: Server.ClearError();
o What It Does: Clears the error so it doesn't get processed
further.
9. CreateObject(): Instantiates a COM object identified by a ProgID.
o Example: object comObject = Server.CreateObject("ProgID");
o What It Does: Creates an instance of a COM object based on its
ProgID, allowing interaction with external components.
How It Works
The ServerUtility class in ASP.NET provides essential methods
(HtmlEncode, HtmlDecode, UrlEncode, UrlDecode, MapPath, Transfer,
GetLastError, ClearError, CreateObject) that help developers manage various
server-side tasks efficiently. These methods are crucial for handling URL
encoding, file paths, error handling, and even interfacing with COM objects,
making them indispensable for building robust web applications.