Recently, I’ve been getting a lot of questions from people who ask how to manipulate the page from an extension in BlogEngine.NET. Most of the times the purpose has been to add a stylesheet or JavaScript reference in the page header dynamically.

It’s actually pretty easy but not that obvious so I thought I’d give an example. The following code inserts a stylesheet into the page header from an extension. Remember that the stylesheet must be placed in your theme folder.


using System;

using System.Web;

using System.Web.UI.HtmlControls;

using BlogEngine.Core.Web.Controls;

using BlogEngine.Core;


[Extension("Test description", "1.0", "Mads Kristensen")]

public class PageTest


  public PageTest()


    // Registers event handlers for serving both posts and pages.

    Post.Serving += new EventHandler<ServingEventArgs>(ServingHandler);

    Page.Serving += new EventHandler<ServingEventArgs>(ServingHandler);



  private void ServingHandler(object sender, ServingEventArgs e)


    HttpContext context = HttpContext.Current;

    if (context != null && !context.Items.Contains("PageTest"))


      // Gets a reference to the serving page.

      System.Web.UI.Page page = context.CurrentHandler as System.Web.UI.Page;

      if (page != null)


        // Creates a stylesheet link reference.

        HtmlLink link = new HtmlLink();

        link.Href = "style.css";

        link.Attributes.Add("type", "text/css");

        link.Attributes.Add("rel", "stylesheet");


        // Adds the stylesheet to the header of the page.



        // Sets a flag so only one stylesheet is added

        context.Items.Add("PageTest", 1);