Programmatically Injecting SEO Friendly Tags In ASP.NET Core

This article will cover:
  • What are SEO friendly tags, and why do we need them?
  • Dynamic layout issues with meta tags because of one Master/Layout/Primary page and several content pages.
  • How to inject the meta tags in ASP.NET Core pages.
  • Example and Testing

SEO Friendly tags are those tags which help us to improve our web ranking in search engines. Most of the search engines usually crawl through websites with some frequency (depending on several factors) and find meta tags which contain the keyword, description, author information and other information in header tags of pages. Then it proceeds for further HTML tags in the body of web pages.

In dynamic websites like ASP.NET Core, it is a bit difficult to manage these tags on content pages because there is one master/layout page usually and all content pages share that page content. One of the ways is you can define the ViewBag or ViewData in the _Layout page and update it in each page to manage the title of the page but others are still an issue, so how do we need to deal with them? The answer is simple, we can dynamically inject them.

Step 1

Create ASP.NET Core MVC Project in Visual Studio 2017,
 
Programmatically Injection Of SEO Friendly Tags In ASP.NET Core 

Step 2

Create a Folder “Helpers” and Inside the Helpers folder add a class as “SEOPageMetaHelper”. this class is used as a data provider, you can use the database or XML or any other data source, but I have used this class for demo purposes for simplicity.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace DynamicMetaTags.Helpers  
  7. {  
  8.     public static class SEOPageMetaHelper  
  9.     {  
  10.         public static IEnumerable<Tuple<string, string, string, string>> Collections  
  11.         {  
  12.             get  
  13.             {  
  14.                 return new List<Tuple<string, string, string, string>>  
  15.                 {  
  16.                    new Tuple<string, string, string, string>("Home/Index""Dynamic Index""Index Description","keyword1,keyword2"),  
  17.                    new Tuple<string, string, string, string>("Home/About""Dynamic About",  "About Description","keyword3,keyword4"),  
  18.                    new Tuple<string, string, string, string>("Home/Contact""Dynamic Contact""Contact Description","keyword5,keyword6")  
  19.                 };  
  20.             }  
  21.         }        
  22.   
  23.     }  
  24. }  

In the next step, you need to create a service that we will inject our main _layout page and use it for meta tags integration.

So, create a service in the Helpers folder “HelperService”

  1. public class HelperService  
  2.     {  
  3.        
  4.         private StringBuilder sb = new StringBuilder();  
  5.   
  6.         public string InjectMetaInfo(string urlSegment)  
  7.         {  
  8.             var metaInfo = SEOPageMetaHelper.Collections.Where(s => s.Item1.Equals(urlSegment,StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();  
  9.   
  10.             //If no match found  
  11.             if (metaInfo == null)  
  12.                 return string.Empty;  
  13.   
  14.             sb.Append("<title>" + metaInfo.Item2 + "</title>");  
  15.             sb.Append(Environment.NewLine);  
  16.             sb.Append($"<meta name='description' content='{metaInfo.Item3}'/>");  
  17.             sb.Append(Environment.NewLine);  
  18.             sb.Append($"<meta name='keywords' content ='{metaInfo.Item4}'/>");  
  19.             string metaTag = sb.ToString();  
  20.             sb = null;  
  21.             return metaTag;  
  22.         }  
  23.     }  

The code is real simple, I just grabbed the specific page's Meta tag information and created a Meta tag, this can be simplified more, but for a demo it’s okay.

Now, we need to register this service as a dependency because we need it to inject in the _Layout page.

Open the startup.cs file and register it as-

  1. services.AddScoped<HelperService>();  

So my startup is looking like this,

  1. public void ConfigureServices(IServiceCollection services)  
  2.   {  
  3.       services.Configure<CookiePolicyOptions>(options =>  
  4.       {  
  5.           // This lambda determines whether user consent for non-essential cookies is needed for a given request.  
  6.           options.CheckConsentNeeded = context => true;  
  7.           options.MinimumSameSitePolicy = SameSiteMode.None;  
  8.       });  
  9.   
  10.       
  11.       services.AddScoped<HelperService>();  
  12.       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  13.   }  

Now, we need to update the _Layout.cs pahe which is in Views/Shared folder and we need to inject the service like this:

  1. @using DynamicMetaTags.Helpers  
  2. @inject HelperService helperService  
  3. <!DOCTYPE html>  
  4. <html>  

Now, we can use the helperService in this page because we injected it in Razor view, so the next piece of code that injects meta tags is:

  1. @{  
  2.     string segements = $"{this.ViewContext.RouteData.Values["controller"]}/{this.ViewContext.RouteData.Values["action"]}";  
  3.     @(Html.Raw(helperService.InjectMetaInfo(segements)));  
  4.     segements = null;  
  5. }  

This code gets the current controller/action segments, constructs them and sends them to HelperService as a parameter, HelperService method returns Meta tag that is rendered in head section of page.

Now the page header looks like:

  1. @using DynamicMetaTags.Helpers  
  2. @inject HelperService helperService  
  3. <!DOCTYPE html>  
  4. <html>  
  5. <head>  
  6.     <meta charset="utf-8" />  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
  8.     <title>@ViewData["Title"] - DynamicMetaTags</title>  
  9.   
  10.     <environment include="Development">  
  11.         <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />  
  12.         <link rel="stylesheet" href="~/css/site.css" />  
  13.     </environment>  
  14.     <environment exclude="Development">  
  15.         <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"  
  16.               asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"  
  17.               asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />  
  18.         <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />  
  19.     </environment>  
  20.   
  21.     @{  
  22.         string segements = $"{this.ViewContext.RouteData.Values["controller"]}/{this.ViewContext.RouteData.Values["action"]}";  
  23.         @(Html.Raw(helperService.InjectMetaInfo(segements)));  
  24.         segements = null;  
  25.     }  
  26.   
  27. </head>  
  28. <body> ..  
  29. // body code   

Now, it’s time to see the actual working demo application

Expect
  • The homepage should show title as “Dynamic Index”
  • The homepage should show meta tag type=”description” as “Index Description”
  • The homepage should show meta tag type=”keyword” as “keyword1,keyword2”
Let me run the project:
 
Programmatically Injection Of SEO Friendly Tags In ASP.NET Core 
 
Result/Output is what we expected
 
Programmatically Injection Of SEO Friendly Tags In ASP.NET Core 

Here, we see that dynamic title, meta tag description, and meta tag keywords have been injected in the main Home/Index view.

Let me try another view like contact and about,

About Page
 
Programmatically Injection Of SEO Friendly Tags In ASP.NET Core 

Contact Page
 
Programmatically Injection Of SEO Friendly Tags In ASP.NET Core 

By default, the ASP.NET core has included the <title> in the _Layout page so I am going to remove that tag because we injected it dynamically

Please Note
Open the _Layout.cshtml file and remove the <title>@ViewData["Title"] - DynamicMetaTags</title> f and now we have only one title tag in the page that we injected.

Conclusion

We can improve our website rank by introducing some Meta tags which expose description and keywords of searching to the search engine and we can get an improved ranking, and in dynamic layouts/master pages, we can dynamically inject the Meta tags information as we did in our ASP.NET Core project.