Update: It is now possible to write extensions that alters the text of the individual posts by using the Post.Serving event. Also on comments using Post.CommentServing
Last week BlogEngine.NET 1.1 was released, but we are already well on the way to version 1.2, which amongst other things will include a unified extension model.
An extension allows you to write a class that can hook up to all the various events that are exposed in the application in a very simple manor. I’ve written a simple extension that stops other websites from bandwidth leeching by referencing your images directly. You can download the complete source code at the bottom of the post.
To transform a class to an extension, all you have to do is to decorate the class definition with an attribute called Extension like so:
[Extension("Stops other websites in displaying your images on their own website")]
public class StopLeechers
The Extension attribute must be fed with a description of the extension you are writing. That’s how we can provide a user interface that lists all extensions nicely with name and description.
Secondly, there must be a default constructor – one without parameters. That constructor will be called when the web application starts, so it’s here we will hook into the events of BlogEngine.NET. Here is how it looks in the StopLeechers extension class:
ImageHandler.BeforeServing += new EventHandler<ImageHandler.FileHandlerEventArgs>(StopReferrers);
Notice that it makes use of the ImageHandler’s BeforeServing event. The ImageHandler is used to serve images that you’ve uploaded and inserted to your blog posts.
Now the event is hooked and we can write the StopReferrers event handler. The event handler will look at the referring URL and determine if it comes from the blog itself or another website. If another website references the image, we will terminate the response and send the HTTP status code 403 Access Denied.
void StopReferrers(object sender, ImageHandler.FileHandlerEventArgs e)
HttpContext context = HttpContext.Current;
if (context.Request.UrlReferrer != null)
if (context.Request.UrlReferrer.Host != context.Request.Url.Host)
context.Response.StatusCode = 403;
The last thing you need to do is to drop the file into the App_Code folder. From the moment the file is dropped, the extension activates.
As mentioned, you can hook your extension up to all the events present in BlogEngine.NET, not just the ImageHandler’s. Here is a list of the events you can use.
- Post.Serving - NEW!
- Post.CommentServing - NEW!
We are adding more before the next release. Especially, we will add events that allow you to change the output of a post. That means that you can do string manipulation and other things to the actual post before it get served to the response stream.
If you can’t wait for the 1.2 release, then get the latest source code from CodePlex. Remember that this is not released yet, so it can be subject to change, but I don’t expect it to.