Select Page

So today’s challenge was to display the Title, Meta description and meta tags on a site I am currently working on for troubleshooting and SEO reasons.

The solution I came up with was to place the following code in the code behind of the masterpage.


protected void Page_Load(object sender, EventArgs e)
        {
HtmlHead headTag = (HtmlHead)Page.Header;
            Response.Write("Title of Page: " + headTag.Title + "");

            foreach (var control in Page.Header.Controls)
            {
                var test = control.GetType();
                if (test.Name == "HtmlMeta")
                {
                    if ((control as HtmlMeta).Name == "Description")
                    {
                        Response.Write("MetaDescription : " + (control as HtmlMeta).Content + "");
                    }
                    if ((control as HtmlMeta).Name == "Keywords")
                    {
                        Response.Write("MetaKeywords : " + (control as HtmlMeta).Content + "");
                    }
                }
            }
}

The HeadTag.Title gives us the Title of the current page.
The foreach loop jumps through each control in the header section of the current page.
Since there can be different types of controls in the header section, we need to check for the type of HtmlMeta.
Then we need to check to see if it is the Description or Keywords and return the content values.

I am sure there are other ways, but this is a really simple way to display the 3 main SEO elements, Page Title, Page MetaTag Description and Page MetaTag Keywords for all the ASP.NET pages that use this master page (or you can place it on each page code behind) without having to view the source code.

Just remember to remove this code before you launch your site 🙂