Web Forms Should Inherit a Custom Class

When doing a web application in .NET, I like to create a custom class that inherits from System.Web.UI.Page I usually call this class “MyWebPage”. In some (most) cases, this class doesn’t add any functionality, it’s just a wrapper. However, when you need to do certain things in your web app, this wrapper is invaluable.

When creating web forms, the first thing I do is change the code behind file, so it inherits from “MyWebPage” rather than default System.Web.UI.Page. This gives the new web form whatever functionality is built into “MyWebPage”.

When is this useful? Previously, I talked about dynamic master pages in a CMS application. By overwriting the PreInit method in “MyWebPage” to include the functionality for dynamic web pages, any new template that inherits “MyWebPage” will automatically receive this functionality. The alternative would be to override the PreInit method in every new template.

I first heard about making this page wrapper when Paul Sheriff gave a talk at an Iowa .Net User Group meeting. The example he gave was that you have a large .NET application. On Friday morning, your boss tells you that by Monday, the web application should log every time a page is hit, this log would be something above and beyond what the web server can log. Without the wrapper, you would have to edit every web form in the application, possibly hundreds of files. With the web forms inheriting from your wrapper class, you simply change this one class, and you enjoy the weekend.

Since then, I’ve heard this talked about on .NET Rocks, and also in this blog post by Brian Mishler.

%d bloggers like this: