.Net

Eat, sleep, code.

.Net Core Copyright tag helper

.Net Core C# Tag Helper
.Net Core Copyright tag helper

I've created a simple copyright tag helper for .Net Core that will read your version information from appsettings.json

I used to use the AssemblyInfo.cs file to extract the version number but .Net Core as removed that file. That's ok though because we can stick our version information into the appsettings file and can get a strongly typed version information with IOptions.

Step 1: Create the node in appsettings.json like so:

"Version": {
    "Company": "Your Co",
    "Major": 2018,
    "Minor": 3,
    "Build": 3,
    "Revision": 1923
  }

Step 2: Create a matching configuration/options cs file:

public class VersionConfiguration
{
	public int Major { get; set; }

	public int Minor { get; set; }

	public int Build { get; set; }

	public int Revision { get; set; }

	public string Company { get; set; }
}

Step 3: Register the configuration in ConfigureServices in Startup.cs:

services.Configure(Configuration.GetSection("Version"));

Step 4: Create a TagHelper that takes an IOptions<VersionConfiguration> in the constructor. .Net Core will handle the injection here.

[HtmlTargetElement("copyright")]
public class CopyrightTagHelper : TagHelper
{
	private readonly VersionConfiguration _version;

	public CopyrightTagHelper(IOptions versionConfiguration)
	{
		_version = versionConfiguration.Value;
	}

	public override void Process(TagHelperContext context, TagHelperOutput output)
	{
		output.TagName = "p";
		output.Content
			.SetHtmlContent($"{_version.Company} &copy; {DateTime.UtcNow.Year} Version: {_version.Major}.{_version.Minor:00}.{_version.Build:00}.{_version.Revision:0000}"
			.Trim());
	}
}

Final Step: Put the tag helper in the footer of your app.

<copyright></copyright>

That's it you're all done! Just change the information in appsettings and the tag helper will do the rest.

comments powered by Disqus

FOLLOW ME!

© Copyright 2018