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,
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace DynamicMetaTags.Helpers
- {
- public static class SEOPageMetaHelper
- {
- public static IEnumerable<Tuple<string, string, string, string>> Collections
- {
- get
- {
- return new List<Tuple<string, string, string, string>>
- {
- new Tuple<string, string, string, string>("Home/Index", "Dynamic Index", "Index Description","keyword1,keyword2"),
- new Tuple<string, string, string, string>("Home/About", "Dynamic About", "About Description","keyword3,keyword4"),
- new Tuple<string, string, string, string>("Home/Contact", "Dynamic Contact", "Contact Description","keyword5,keyword6")
- };
- }
- }
-
- }
- }
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”
- public class HelperService
- {
-
- private StringBuilder sb = new StringBuilder();
-
- public string InjectMetaInfo(string urlSegment)
- {
- var metaInfo = SEOPageMetaHelper.Collections.Where(s => s.Item1.Equals(urlSegment,StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
-
-
- if (metaInfo == null)
- return string.Empty;
-
- sb.Append("<title>" + metaInfo.Item2 + "</title>");
- sb.Append(Environment.NewLine);
- sb.Append($"<meta name='description' content='{metaInfo.Item3}'/>");
- sb.Append(Environment.NewLine);
- sb.Append($"<meta name='keywords' content ='{metaInfo.Item4}'/>");
- string metaTag = sb.ToString();
- sb = null;
- return metaTag;
- }
- }
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-
- services.AddScoped<HelperService>();
So my startup is looking like this,
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options =>
- {
-
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
-
-
- services.AddScoped<HelperService>();
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- }
Now, we need to update the _Layout.cs pahe which is in Views/Shared folder and we need to inject the service like this:
- @using DynamicMetaTags.Helpers
- @inject HelperService helperService
- <!DOCTYPE html>
- <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:
- @{
- string segements = $"{this.ViewContext.RouteData.Values["controller"]}/{this.ViewContext.RouteData.Values["action"]}";
- @(Html.Raw(helperService.InjectMetaInfo(segements)));
- segements = null;
- }
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:
- @using DynamicMetaTags.Helpers
- @inject HelperService helperService
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>@ViewData["Title"] - DynamicMetaTags</title>
-
- <environment include="Development">
- <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
- <link rel="stylesheet" href="~/css/site.css" />
- </environment>
- <environment exclude="Development">
- <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
- asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
- asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
- <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
- </environment>
-
- @{
- string segements = $"{this.ViewContext.RouteData.Values["controller"]}/{this.ViewContext.RouteData.Values["action"]}";
- @(Html.Raw(helperService.InjectMetaInfo(segements)));
- segements = null;
- }
-
- </head>
- <body> ..
-
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:
Result/Output is what we expected
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
Contact Page
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.