Extend ASP.NET with HTTP modules

by iatanasov 25. September 2007 07:04

Like in other .NET-applications, exception-handling is also available in ASP.NET-applications. There are a few extensions and special features for exception-handling in ASP.NET that will be explained in this article: Predefined IHttpModules allow you to process incoming requests and outgoing responses to and from an ASP.NET application. This article offers a closer look at using HTTP modules in ASP.NET applications.

Introduction to HTTP modules

ASP.NET HTTP modules provide access to incoming and outgoing traffic to a Web application. They are similar to Internet Server Application Programming Interface (ISAPI) filters in that they run for all requests, but HTTP modules are written in managed code and are fully integrated with the lifecycle of an ASP.NET application.

HTTP modules provide pluggable functionality to ASP.NET applications. These modules are added to the request pipeline before and after the ASP.NET HTTP handler fires. HTTP modules are different than HTTP handlers. HTTP modules are called for all requests and responses, whereas HTTP handlers run only in response to specific requests.

HTTP modules and the Global.asax file available in all ASP.NET applications provide the same functionality, but the implementation is a bit different. The Global.asax file requires code in the application, thus compilation when it changes; HTTP modules are completely separate.

A great aspect of HTTP modules is that they are built without affecting existing applications — albeit the extensible  architecture. These are easily added or removed to and from an ASP.NET application via the Web configuration (web.config) file.

Some common uses of HTTP modules include the following:

  • Headers: You can easily inject custom header information into each page.
  • Logging: You can easily gather logging or statistical data for every request. The creation of a custom HTTP module provides a central location for logging as opposed to code in every page.
  • Security: You can perform custom authentication or security checks on each page request. You may filter based upon user credentials, IP address, etc. The ASP.NET MemeberShip Provider work in this style.

How HTTP modules work

HTTP modules are registered in the web.config file. This ties the module to an application. As a result, when ASP.NET creates an instance of the HttpApplication class for an application, instances of any modules that have been registered are created as well. The module’s Init method is called when it is instantiated.

Within the Init method, the module subscribes to one or more events from the HttpApplication object. These events correspond to user actions within an ASP.NET application. These events include the following:

  • AcquireRequestState: This is the event you call to acquire or create the state for the request.
  • AuthenticateRequest: This event fires when a security module needs to authenticate the user before it processes the request.
  • AuthorizeRequest: This event is fired by a security module when the request needs to be authorized after authentication.
  • BeginRequest: This event signals that a new request is beginning.
  • Disposed: This event signals the application is ending, so it allows the module to perform clean up operations.
  • EndRequest: This event signals that the request is ending.
  • Error: This event is called when an error occurs during request processing.
  • PostRequestHandlerExecute: This event signals that the handler has finished processing the request.
  • PreRequestHandlerExecute: This event signals that the handler for the request is about to be called.
  • PreSendRequestContent: This event signals that content is about to be sent to the client.
  • PreSendRequestHeaders: This event signals that HTTP headers are about to be sent to the client.
  • ReleaseRequestState: This event signals that the handler has finished processing the request.
  • ResolveRequestCache: This event is triggered after authentication.
  • UpdateRequestCache: This event fires after a response from the handler.

An HTTP module may use any of these events.

Creating an HTTP module

You build a custom HTTP module using the IHttpModule interface, which you can find in the System.Web namespace. You want to possiblity to handle errors is in an own IHttpModule. To define it, you have to implement the interface IHttpModule and bind your error-handler in this class:

public void Init(HttpApplication app);
public void Dispose();
The Init method is important since it is called when the HTTP module is called to process incoming requests or outgoing responses. Calls to events (from the previous list) are placed in this method. If one of the events from the HttpApplication class is used, the code to handle the event must be included as well. This includes a delegate, the method, hooking to the event, and so forth.

Once a module is built, it may be registered by way of the httpModules section of the web.config file as the following snippet illustrates:

<system.web>
<httpModules>
<add type="[Class], [Assembly]" name="[ModuleName]" />
<remove type="[Class], [Assembly]" name="[ModuleName]" />
<clear />
</httpModules>

The best way to grasp the use of HTTP modules is to build one. HTTP modules are created as a class library. When using Visual Studio, a reference to the System.Web namespace is added to the project to access the required classes.

The following C# sample demonstrates a simple HTTP module that is tied to the BeginRequest and EndRequest events for a user request. The code displays a simple message in the browser stating the event fired. The events are registered in the module’s Init method with a method created for each event handled.

public class ErrorModule : IHttpModule

{

public ErrorModule()

{

}

#region IHttpModule Members

public void Dispose()

{

}

public void Init(HttpApplication context)

{

context.Error
+= new EventHandler(context_Error);

}

void context_Error(object sender, EventArgs e)

{

Exception e
= HttpContext.Current.Server.GetLastError();

// Clear the error so that it doesn't occur again in

// the Application_Error-handler

HttpContext.Current.Server.ClearError();

HttpContext.Current.Response.Redirect(
"ErrorPage.htm");

}

#endregion

}

 

So what is the benefit of using an own HttpModule. Well, the name already says it: You have a modularization for your error-handling. You can change your implementa

tion at one place without touching your application-logic and you can change the errorhandling of your appliation by defining another HttpModule and configuring it in your web.app..

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

asp.net 2.0

You are Beginner: Learn XHTML ASP.NET and Database

by iatanasov 2. August 2007 05:11

In the last two weeks, three friends have approached me asking how they can get into Web development: a university professor who wants to create a virtual community for his students, an owner of a language school who wants to get into e-commerce, and an English teacher looking for a lucrative career move. My advice to all of them was the same: learn XHTML, ASP.NET and database servers.Why XHTML

XHTML is the core of the Web

From the simplest Web site to the most complex e-commerce solution, XHTML is the script that is ultimately sent down to the visitors’ browsers. There is no getting around it: if you want to do Web development, you need to know XHTML. The good thing is that HTML is relatively easy to learn. It is not a programming language so there are no for-next loops, no variables, and nothing about sessions or functions to learn. It is just a mark-up script, which means that you merely surround text with tags which tell the browser to treat that text specially. To see how easy it is, take my Learn HTML by the end of the hour you will have created your first Web site and learned the most important XHTML tags. It’s really that easy.

After you have made your first home page come up in a browser, learn more by getting an XHTML editor such as Dreamweaver or VIsual Studio Web Developer which allows you to create pages in a Word-like environment and then look at the automatically generated XHTML text. Such an editor is one of the best XHTML learning tools that there is - if you want to learn how to create a colored table, then create one and look at the XHTML code. To learn more, change the code a bit and look at the table again. Keep doing this until you get an understanding of how the XHTML code affects the display in the browser. XHTML is simple enough that experimenting in this way will speed-teach most of practical XHTML skills you need.

After you get a sense of the relationship between XHTML tags and their output in the browser, get a good-sized, comprehensive book on XHTML and work through it at quick pace. It’s not important you understand each tag in depth, but it is important that you have an overview of all the XHTML tags so that you can spot them in the code and know what is available to you when you are designing pages. After you have worked through a book like this, you will have a good theoretical basis of XHTML, which is important when you start programming in ASP.NET.

ASP.NET is a powerful server-side script

Only knowing XHTML is limiting because all you can do is create static pages. What if you have a list of students, for example, which you want to sometimes display sorted by last name, sometimes sorted by grade, and sometimes want to show only those who have finished a specific assignment? For this you need to have this information in a database and use ASP.NET to dynamically send only the information you want to your visitors’ browsers.

To develop sites with ASP, you first need to set up the ASP.NET programming environment on your computer, which can be difficult if you have never done it before. The easiest way to do this is to take visual studio 2005 

and sql server 2005  which will enable you to get an ASP.NET developing environment up within the hour, complete with a working ASP.NET page which reads data from an MS SQL database.

Next you need to learn ASP.MET. For most non-programmers this is going to involve a learning curve.  Also, if you have never programmed in a client/server environment, you will go through a paradigm shift trying to understand the five server objects: application, server, session, response and request. The good thing is that you don't have to understand everything about ASP.NET to start making useful ASP.NET applications. My advice is to get a good book on ASP.NET and work through it at your own pace pulling out of it only that which you can use for your own particular Web application project, then keep the book within arm's reach for reference. 

Database connectivity: where the rubber hits the road

ASP.NET applications without database are not much more useful than plain XHTML pages. Hence, you will want to learn database connectivity from the very beginning of your ASP.NET learning. Spend your time learning how to read, write, delete and edit data in databases from your ASP.NET pages. This is where the real power of an ASP.NET application lies.

Although ASP.NET can talk to almost any database, Microsoft SQL 2005 is the best database to use with ASP.NET, and you will need to have a copy installed on your machine before you begin programming database connectivity into ASP.NET. MS SQL 2005 will work, too, of course. You can go to microsoft.com/downloads and there you search this product.

Today, you can get excellent books on database connectivity using ASP.NET, and in our forums have hundreds of code samples for you to try out and learn from.

Hosting your ASP Web site

When it is time to put your ASP.NET Web site on the Internet for others to use, Web hosting services such as aspspider.com will host your database-generated ASP Web site for free.

Not easy, but possible and very powerful

In the final, learning ASP.NET and database connectivity is not as easy as learning how to use other Windows applications. Programming involves another level of involvement and learning which for some is simply not a joy. However, if you are excited about learning basic programming skills and can invest a couple of months learning and experimenting with this technology, you will come out with skills with which you can create robust and useful database-generated Web applications such as virtual classrooms or e-commerce Web sites. You will also be able to market yourself as a highly paid Web developer. More power to you!

Currently rated 4.7 by 3 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

asp.net 2.0 | web design | web development

How Can I Improve performance of ASP.NET Application

by iatanasov 29. July 2007 06:44

 

Step1: Learn "Hot to work with strings?"

If you are c++ programmer and start with modern languages while Delphi, c# or Java, there have thausands of lines writen for working with strings.

Never not use:

    string result = ""; //instead result = string.Empty.

For this method of initialization of string variable Microsoft are make couple of optimization.

If you want to format same string, don't write:

    result = var1 + " this is " + var2 + " the best " var3 + " ."; //where var 1-3 are string variable

Just use:

    result = String.Format("{0} this is {1} the best {2} ."

If you must concatenated  more that four string, in language exist StringBuilder. I'm make test with 1000 concatanations of strin. For "result += result" this take about twenty 

seconds, instead for StringBuilder is three seconds. 

If you campare strings, don't use equals operator (this is stupid  least). Use String.Compar() or string result = "test", result.Equals("tests")

Step2: Use "Using" block for working with database and file system.

if you open file or database connection just write:

        using(SqlConnection connection = new SqlConnection(connectionString))
        {
             connection.Open()
        } //after programs pass this line, connection is closed

What deliver this functionallity for you?

  1. if you forgot to close connection, it's closed.
  2. couple of lines code, that you have to write. 

Step4: Use generics  List instead ArrayList. 

ArrayList object make boxing and unboxing in every operation with it, for this reason Microsoft ® release List<T> (generic lists) with .net 2.0. When they are make optimization , we just have to use it.

Never don't write:

    ArrayList customers = new ArrayList();  // List<Customer> customer = new List<Customer>();

    customers.add(new Customer());         // it's same

    Customer temp = customers[i] as Customer; //  Customer temp = customers[i];//without unboxing;

Step5: Don't use ssl on every pages

I'm look person that write e-commerce application and they put ssl on every web pages. This isn't right decision, you must implement you chec-out process with ASP.NET wizard

and put user iteration only on couple of pages. When user browse web site , there no reason to have SSL on every page. If you open sites while amazon i yahoo shopping you will

see,  that use ssl when you buy product and must enter same sensitive information.

For you stay problem to define which pages exatly have need to be put on SSL line, this one will be perfect fix the problem with your ASP.NET perfomance.

Conclusion:

  • Working with string is imporatnt for web development.
  • Minimazing using of ArrayList, instead use Custom Obgects with Generic List.
  • Minimazing using of SSL, this will put down your web server. 

 

Currently rated 4.0 by 3 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

asp.net 2.0 | web development

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

About the author

Ivan Atanasov - web developer
E-mail me Send mail Subscribe Feed

Calendar

<<  July 2008  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008 it-coder.com

    Sign in