Creating a CDN Helper in Dot Net CoreMartyn · 08 Sep 2020 · ~2 minutes · Comments
In my previous post, I talked about static content hosting, if you are a developer, then this helper will save you a bunch of time. Join me in this post as we create a HTML helper in Dot Net Core to reference files in your content delivery network.
Creating a custom helper is easier than you would think. So to keep things easy for us, we are going to use the configuration file appsettings.json to store the base path to our CDN. This will make it easier to change our root without having to update the whole of our application.
First of all, I am using Dot Net Core for this, you can easily achieve the same thing using the regular .NET Framework. Create a new class, I called mine CdnUrlHtmlHelper.cs, this makes it easy to see what it’s used for.
Within this file you will have two classes. But first, let’s have a look at the easiest part. This is reterieving the configuration setting from the configuration file.</p>
Using dependency injection within Dot Net Core, I am able to access the configuration settings easily using a private property. I then pass the
IConfiguration interface into the constructor of the class to set the private property. Any of my configuration settings can now be accessed using the
The next step is todefine a public static class for our actual helper. I shall move onto the usage shortly. The idea here is that I pass in the content path, then retrieve the base URL from configuration and build the URL to return back to the view engine.
I can then call this very simply, check out the examples below.
Posted In: Web & Mobile · C#, Dot Net, Helper, CDN, Programming, Web