Skip to main content

ASP.NET Using Request Information


Using Request Information


In situation one may want to know about the client browser type and generate contents accordingly.

Request.Browser
Methods include: GetClrVersions(), IsBrowser(BrowserType)

Properties Include: ActiveXControls(Supported or Not), AOL (Client is AOL Browser), BackgroundSounds(<bgsound> supported or not), Browser (Browser string), ClrVersion( installed version), Cookies(supported), Crawler (Browser is a search engine or not), Frames(HTML Frames Supported or not), IsColor(color or grayscale), IsMobiledevice, JavaApplets(Supported or not), JavaScript, JScriptVersion, MobieDeviceManifecturer, MobileDeviceModel, MSDOMVersion, Tables, VBScript, Version, W3CDomVersion, Win16, Win32.


Pages and Application context overview:

ASP.NET provides many objects to examine the request and response information.

Response: HttpResponse.

BinaryWrite, AppendHeader, Clear, ClearContents, ClearHeaders, End, Flush, Redirect (302), TransmitFile( Without buffering), Write(Writes with buffering), WriteFile (Alternative to Server.Transfer, by sending Http 302 code and new page url. Similar to Response.Redirect),
WriteSubsitution(Uses HttpResponseSubsitutionCallback delegate to make replacements in cached output, alternative is to use Substitution control),

Important properties include:
Cookies, Buffer (if true response buffered before response), Cache (expiry time, privacy policy), Expires (Page expiry time at client end), ExpiresAbsolute(absolute date and time for expiration), Status and StatusCode(Get and Set Http Status code).

Request: HttpRequest

MapPath: Converts relative to absolute path. /About.htm à C:\inetpub\wwwroot\about.htm

SaveAs: save the request file.
ValidateInput: validate input for potentially dangerous input from user.

Important properties of Request:
ApplicationPath: Virtual root path to app.
AppRelativeCurrentExecutionFilePath: returns relative path + (~). ~/About.htm
Browser: Examine Browser.
ClientCertificate: Security certificate if client sent some one.
Cookies: Cookies sent by browser.
FilePath: virtual path of the current request.
Files: Files uploaded by client.
Headers: HttpHeaders collection
HttpMethod: HttpMethod used like Get, Post, or Head.
IsAuthenticated: Indicates if the client is authenticated.
IsLocal: If client is from local network.
IsSecureConnection: True if connection uses HTTPS.
LogonUserIdentity: WindowsIdentity that represents the current user.
Params: combination of QueryString, Form, ServerVariables, and Cookies.
Path: Virtual path of the current request.
PhysicalApplicationPath: Physical path of the root directory.
PhysicalPath: Physical path of the current request.
QueryString: Key/Value collection of query.
RawURL and URL: URL of the current request.
TotalBytes: Length of request.
URLRefer: URL of the page from which the user is being redirected to this page.
User Agent: User agent string i.e. “Internet Explorer” etc.
UserHostAddress: Client’s IP.
UserHostName: DNS of the remote client.
UserLanguages: Sorted string array of languages (Arabic, English, German)


Server: HttpServerUtil à for processing of URLs, Path, and HTML.

ClearError(): Clears the last error:
GetLastError(): return previous exception.
HtmlDecode(): Removes Html markups from string.
HtmlEncode(): To Display a page and convert “<” to “&lt
MapPath(): Return physical path from virtual path.
Transfer(): Stops processing the current page and starts processing of next page.
URLDecode(): Decodes a string contained in URL. Client à Server
URLEncode(): Encodes a string contained in URL. Server à Client
URLPathEncode(): Encodes path portion of the string.
URLTokenDecode(): Decodes a URL string token to its equivalent byte array using 64 base.
URLTokenEncode(): Encodes a byte array to URL for better HTTP Transmission.


Context: HttpContext
It provides access to many objects that are redundant like Cache, Request, Response, Server and Session. Some unique methods include:

AddError(): Adds an error that can be retrieved by Server.GetLastError().
ClearError(): Equivalent to Server.ClearError().
RewritePath(): Actually requested path can differ from the internal path. Used especially when cookieless session is used to remove session information from the path.

Important Properties include:
AllErrors: Collection of unhandled exceptions on the page.
IsCustomErrorEnabled: True if custom errors are enabled.
IsDebuggingEnabled: True if Debugging is enabled.
Timestamp: Timestamp for Http request.

Accessing Web Page Headers:

HTML Page header contains information like stylesheet to use, Page Title, and Metadata.
Title may be required to be modified for search result pages so that when adding to favorites the criteria also being appended to Page Title.

Page.Header.Stylesheet enables you to call CreateStyleRule and RegisterStyle method.

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

Asynchronous Execution in ASP.NET

Asynchronous Execution: Two ways either implement IHTTPAsyncHandler interface or in ASP.NET 2.0 set <%@ Page Async=”true” %>. The second option implements IHTTPAsyncHandler interface automatically for the page when parsed or compiled. AddOnPreRenderCompleteAsync ( new BeginEventHandler(BeginTask), new EndEventHandler(EndTask)); AddOnPreRenderCompleteAsync() shoud be called in Page_load. The BeginEventHandler and EndEventHandler are delegates defined as follows: IAsyncResult BeginEventHandler( object sender, EventArgs e, AsyncCallback cb, object state) void EndEventHandler( IAsyncResult ar) AsyncProcess starts and completes between PreRender and PreRenderComplete. Other way to perform Async Task is using AsyncPageTask structure. It also allows multiple tasks to execute simultaneously. void Page_Load (object sender, EventArgs e) { PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginTask), new EndEventH...