Blog / SEO
How to Dynamically Inject JSON-LD Structured Data in .Net Core MVC
  • Dec 05, 2020
  • 95
  • 69

We have known about how Structured Data helps Google to understand the content of your website pages as well as how JSON-LD Structured Data looks like in your page. To make your website more likely to be recognized by Google and reduce the amount of your manual work on Structured Data, we will see how to dynamically inject JSON-LD Structured Data into your .Net Core MVC project.


Advertisement
 


1. What is JSON-LD?

JSON-LD is a recommended structured data to be used in your website because it is the heir of the JSON format and allows linked data to operate in a Web-scale environment. The idea behind this notation is to provide search engines with contextual information about a web page using semantic web technologies. 

2. How to Dynamically Inject JSON-LD Structured Data?

If you have a dynamic website which is updated often, you should come up with a way that the Structured Data is injected dynamically. In this tutorial, we will see how I did it in my .Net MVC project.

There are many type of Structured Data which can be found on Google website. In this post, I will focus on the Article Structured Data since my website is a blog which is mainly about articles. You can implement the same approach for different Data Structured listed by Google in their website.

This is an example of JSON-LD Structured Data for Articles on Google:

<html amp>
  <head>
    <title>Article headline</title>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "NewsArticle",
      "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "https://google.com/article"
      },
      "headline": "Article headline",
      "image": [
        "https://example.com/photos/1x1/photo.jpg",
        "https://example.com/photos/4x3/photo.jpg",
        "https://example.com/photos/16x9/photo.jpg"
       ],
      "datePublished": "2015-02-05T08:00:00+08:00",
      "dateModified": "2015-02-05T09:20:00+08:00",
      "author": {
        "@type": "Person",
        "name": "John Doe"
      },
       "publisher": {
        "@type": "Organization",
        "name": "Google",
        "logo": {
          "@type": "ImageObject",
          "url": "https://google.com/logo.jpg"
        }
      }
    }
    </script>
  </head>
  <body>
  </body>
</html>


Advertisement
 


Step 1: Create a ArticleLdJsonObject class

This class represent the LD-JSON Structured Data for an Article object. We override the ToString method by using JsonConvert.SerializeObject to generate the LD-JSON format string.

Note: Remember to add Newtonsoft.Json from Nuget Package to Serialize the object into JSON string format.

Create a class: ArticleLdJson.cs

using Newtonsoft.Json;
 
public class ArticleLdJson
{
    public string context { get; set; } = "https://schema.org";
 
    public string type { get; set; } = "NewsArticle";
 
    public MainEntityOfPage mainEntityOfPage { get; set; }
 
    public string headline { get; set; }
 
    public List<string> image { get; set; } = new List<string>();
 
    public string datePublished { get; set; }
 
    public string dateModified { get; set; }
 
    public Author author { get; set; }
 
    public Publisher publisher { get; set; }
 
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this)
            .Replace("context", "@context")
            .Replace("type", "@type")
            .Replace("id", "@id");
    }
}
 
public class MainEntityOfPage
{
    public string type { get; set; } = "WebPage";
 
    public string id { get; set; }
}
 
public class Author
{
    public string type { get; set; } = "Person";
 
    public string name { get; set; }
}
 
public class Publisher
{
    public string type { get; set; } = "Organization";
 
    public string name { get; set; } = "Lucasology";
 
    public Logo logo { get; set; } = new Logo();
}
 
public class Logo
{
    public string type { get; set; } = "ImageObject";
 
    public string url { get; set; }
}


Step 2: Create ILdObjectManager and LdObjectManager classes

We will implement dependency injection and create separate Manager class for LD-JSON object business logic management. By doing so, we can separate the logic layer of LD-JSON object from other entities in our project.

Create an interface: ILdObjectManager.cs

public interface ILdObjectManager
{
    string GetArticleLdObject(Post post);
    string GetOrganizationLdObject();
    string GetBreadcrumLdObject(List<string> names, List<string> urls);
    string GetCarouselLdObject(List<Post> posts);
}

Create a class: LdObjectManager.cs which implements ILdObjectManager interface

public class LdObjectManager : ILdObjectManager
{
    private readonly string contentRootPath = Directory.GetCurrentDirectory();
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IHostingEnvironment _hostingEnvironment;
 
    public LdObjectManager(IHttpContextAccessor httpContextAccessor, IHostingEnvironment hostingEnvironment)
    {
        _httpContextAccessor = httpContextAccessor;
        _hostingEnvironment = hostingEnvironment;
    }
 
    public string GetArticleLdObject(Post post)
    {
        List<string> imgList = new List<string>();
        imgList.Add($"https://{_httpContextAccessor.HttpContext.Request.Host.Value}/Uploads/BlogImages/" + post.Thumbnail);
        ArticleLdJson article = new ArticleLdJson()
        {
            mainEntityOfPage = new MainEntityOfPage()
            {
                id = $"https://{_httpContextAccessor.HttpContext.Request.Host.Value}/?url=" + post.Content
            },
            headline = post.Title,
            image = imgList,
            datePublished = post.PublishedDate.ToString("yyyy-MM-dd"),
            dateModified = post.UpdatedOn.ToString("yyyy-MM-dd"),
            author = new Author()
            {
                name = post.AuthorName
            },
            publisher = new Publisher()
            {
                logo = new Logo()
                {
                    url = $"https://{_httpContextAccessor.HttpContext.Request.Host.Value}/Uploads/UserImages/blog-icon_269d.jpg"
                }
            }
        };
 
        return article.ToString();
    }
}


Step 3: Add dependency injection for LdObjectManager in StartUp.cs

In StartUp.cs class, add below line of code in ConfigureServices

StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
   //Omitted Code
   //...
    
   services.AddScoped<ILdObjectManager, LdObjectManager>();
 
   //... 
}


Step 4: Dynamically inject LD-JSON Structured Data into View

We will inject the LD-JSON value, which is gotten by calling GetArticleLdObject method from Manager class, into the html header in _Layout.cshtml. We can save the LD-JSON value in ViewBag when we get the article data from BlogController and pass it to the view.

In BlogController.cs

public class HomeController : Controller
{
   private readonly ILdObjectManager _ldObjectManager;
   public HomeController(ILdObjectManager ldObjectManager)
   {
      _ldObjectManager = ldObjectManager;
   }
 
   public IActionResult Index(string url)
   {
      //Ommited Code
      //...
 
      var post = _blogManager.GetPostByUrl(url);
      ViewBag.LdJsonObject = _ldObjectManager.GetArticleLdObject(post);
 
      //...
   }
}


In _Layout.cshtml:

<html lang="en" amp>
<head>
    <meta charset="utf-8" />
 
    @if (ViewBag.LdJsonObject != null)
    { 
        <script type="application/ld+json">
            @Html.Raw(ViewBag.LdJsonObject)
        </script>
    }
 
</head>
</html>

Now, you can run your application, the header will be rendered like in the screenshot below if you go to the article page (the highlighted lines in the screenshot below):


Advertisement
 


3. How to Test your LD-JSON injected page?

You can test your LD-JSON injected page by going to Google Search Console Rich Results Testing Tool. When you land into the page, you can copy -paste the article URL into the Fetch URL field and click on Test URL like below:


Then, if the LD-JSON is valid, you will receive a message saying: "Page is eligible for rich result" like below:

Done! I hope you enjoy the tutorial and wish you are able to implement it successfully! See you next time! 


Search text in Stored Procedure in SQL SELECT DISTINCT o.name AS Object_Name, o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o ...

Using cherry-pick to select specific commits for your Pull Request.1. Create a new branch based on the target of the Pull Requestgit branch cherry-branch origin/master2. Switch to a new branchgit chec ...

After deployment Angular and API on IIS, it's working fine unless I refresh the page. Once refreshed, the web encountered 404 error. In this article, I will explain how to resolve this.Since Angular i ...

There are some benefits of keeping both UI and API parts in the same place for small projects. In this article, I will explain how I did to deploy Angular Web and ASP .Net Core API in the same folder ...

I got CORS error after publishing my API and Angular app to IIS even though CORS is enabled and the origins of the Angular app is added. Below is how I resolved this issue.Just simple, make sure you s ...

In Object-Oriented Programming, S.O.L.I.D refers to the first five design principle for the purpose of making software designs more understandable, flexible, and maintainable. The principles was first ...

1. The Situation:Error Message:&nbsp;Pulse Secure Application failed to load Java. Please install correct JRE version.Description: This issue happens when I'm using a M1 Mac with a correct version of ...

Below is how to decrypt/convert a Hex string value into text using VB.Net:Decrypting Hex string value to string in VB.Net Function HexToString(ByVal hex As String) As String Dim text As New Sy ...

After a month of publishing on Google Play, Jungle Words has made it to the Top Android Games To Try Out In April 2021. Please check it out!&nbsp;GameKeys.netGameKeys is a website which introduces gam ...