TheDeveloperBlog.com


C# Application_BeginRequest Example

Application_BeginRequest is an event handler. It is part of the ASP.NET website system. The Application_BeginRequest method is executed on all requests handled by the ASP.NET runtime. We look at the Application_BeginRequest event handler.


Example. First, this event handler is declared in a class that derives from HttpApplication. In such classes, the Application_BeginRequest method is automatically used when a request is received.

Note: We determine the important properties of the request, and then render the correct web page depending on those properties.

The method uses the HttpWorkerRequest type as well as a custom hashtable implementation to render object types stored in memory. Finally, the response is terminated and the page is sent over the network.

HttpWorkerRequest Example
Example event handler: C#

internal unsafe protected void Application_BeginRequest(object sender, EventArgs e)
{
    // Get objects from ASP.NET runtime for request and response processing.
    // ... Use inline code and Type cache to get the worker to avoid method overhead.
    HttpContext context = base.Context;
    HttpResponse response = context.Response;
    HttpWorkerRequest worker = ((IServiceProvider)context).GetService(_workerType) as HttpWorkerRequest;
    string key = worker.GetRawUrl();
    /*
     *
     * Begin pasted code to perform lookup. [Inlined]
     *
     * */
    const int val = 352654597;
    int num = val;
    int num2 = val;
    fixed (char* str = key)
    {
	int* numPtr = (int*)str;
	for (int i = key.Length; i > 0; i -= 4)
	{
	    num = (((num << 5) + num) + (num >> 27)) ^ numPtr[0];
	    if (i <= 2)
	    {
		break;
	    }
	    num2 = (((num2 << 5) + num2) + (num2 >> 27)) ^ numPtr[1];
	    numPtr += 2;
	}
    }
    int pos = ((num + (num2 * 1566083941)) &
	int.MaxValue) % FixedStringDictionaryStatic._prime;
    // Search.
    for (int i = FixedStringDictionaryStatic._buckets[pos];
	i >= 0;
	i = FixedStringDictionaryStatic._nexts[i])
    {
	if (string.Equals(FixedStringDictionaryStatic._keys[i], key))
	{
	    FixedStringDictionaryStatic._values[i].Render(worker, response);
	    goto Complete;
	}
    }
    /*
     *
     * End pasted code that did lookup. [Inlined]
     * Go to was added and Render method added.
     *
     * */
    Fallback.Render();
Complete:
    // Set short local cache.
    // ... For all responses on the site.
    worker.SendKnownResponseHeader(HttpWorkerRequest.HeaderCacheControl, _cacheControl);
    // Complete.
    base.CompleteRequest();
}

This code example won't compile for you because it has several external dependencies. However, conceptually it can show you how an Application_BeginRequest event handler can be used to process all incoming requests over the network.

The unsafe modifier is applied to this event handler. The unsafe code in the method is the hash code computation for the string. The url sent by web browsers to the server is hashed directly in this method.

It uses inlined methods. The method uses manually inlined code statements that were copied from elsewhere in the project. This is a difficult optimization but can sometimes significantly improve performance.

Inline Optimization

Note: It is used here because this method is executed on every request to the site. This totals thousands of requests per hour.

The method uses the goto statement. While many programmers are taught to avoid goto, in certain cases such as this one it is harmless. This is the kind of method that must be carefully tested. All pages go through this logic.

Goto Examples: Loops and Switch

Performance. This method is executed on every request to the website. On a local server, it requires about one fifth of a millisecond to execute, and most of that time is spent in the Render method.

Benchmark

Summary. The Application_BeginRequest event handler can be set up to process all network requests, and this can result in an efficient website system. Using unsafe code and goto statements can have benefits, although these factors are not critical.