Social Meta Tag Generator

Published on Sunday 05 July 2020
Categories: Programming and Code |

Social Meta Tag Generator

This simple helper function generates social media meta tags for web pages for Google, Schema.org, Twitter and Open Graph for Facebook etc using C#.

The code and class can be downloaded from github.com/briandorey/Social-Meta-Tag-Generator

In SocialMeta.cs Edit lines 47 and 48 to add your Twitter ID. Edit line 56 to add your business or website name.

This demo uses asp.net master pages and you need to include this tag in the HEAD section of the page.

<asp:Literal ID="LiteralMeta" runat="server"></asp:Literal>

This to disable the normal html title tag, add:

<title visible="false" runat="server"><%-- hack to turn the auto title off --%></title>

In the page load function you add the new Social Meta code with the following:

protected void Page_Load(Object Src, EventArgs E)
{
    SocialMeta sm = new SocialMeta();
    sm.Title = "Page Title";
    sm.Description = "Your meta description";
    sm.Image = ""; 
    sm.Url = "";  
    sm.MakeSocial();
}

The class uses the following:

Create an instance of the SocialMeta object

SocialMeta sm = new SocialMeta();

Set the page title:

sm.Title = "Page Title";

Set the Meta Description tags

sm.Description = "Your meta description";

Set the page image

sm.Image = "";

Set the page canonical url, this is optional and the code will use the HttpContext.Current.Request.Url.AbsoluteUri if not supplied.

sm.Url = "";  

Now we create the tags and assign to the literal in the master page head section.

sm.MakeSocial();

If you wanted to return a string rather than use the Masterpage functionality, change

public void MakeSocial()

to

public string MakeSocial()

Next remove the following lines

var pageHandler = HttpContext.Current.CurrentHandler;
        if (pageHandler is System.Web.UI.Page)
        {
            Literal litStreamHtml = (Literal)((System.Web.UI.Page)pageHandler).Master.FindControl("LiteralMeta");
            litStreamHtml.Text = sbSharing.ToString();
    }

Replace with:

return sbSharing.ToString();

Permalink


0 Comments



Leave a comment

About Me

Brian Dorey

Welcome to my blog, here you will find my projects and other things.
I make websites and manufacturer and sell expansion boards for the Raspberry Pi range of computers.

AB Electronics Raspberry Pi shop

Social Media

Popular Posts

Small image for Raspberry Pi Zero W external antenna mod

Raspberry Pi Zero W external antenna mod
04 MARCH 2017
91,495 views

Small image for Ford Sync 3 USB Drive Music Playlists

Ford Sync 3 USB Drive Music Playlists
22 OCTOBER 2016
62,157 views

Small image for Echo Dot 3rd Gen Smart speaker Teardown

Echo Dot 3rd Gen Smart speaker Teardown
21 JULY 2019
59,371 views

Small image for DIY Pick and Place V2 Project Complete

DIY Pick and Place V2 Project Complete
23 NOVEMBER 2013
35,964 views