In my model class, I am trying to read a value from appsettings.json and set CDN url of the images, according to the environment (development, production). It is a .net core app.
Model
public class Person
{
public int Id { get; set; }
public int ProfileImageUrl => $"{Configuration["CdnUrl"]}/profiles/{Id}.jpg"
}
Index.cshtml (Razor Page)
@page
@model IndexModel
<img src="@Model.ProfileImageUrl " />
Index.cshtml.cs
public async Task OnGetAsync()
{
Person = await _context.Person.FirstAsync();
}
App settings
appsettings.Development.json
{
"CdnUrl": "/images"
}
appsettings.Production.json
{
"CdnUrl": "https://images.domain.com"
}
How can I achieve this? Thanks in advance
There's a simple way to do that . Since you've configured the CdnUrl in your appsettings.json file , let's create a TagHelper with an IConfiguration property injected , so that we can calculate the final URL at runtime:
[HtmlTargetElement("cdn-img")]
public class CdnImgTagHelper : TagHelper
{
public IConfiguration Configuration{ get; set; }
public CdnImgTagHelper(IConfiguration configuration) {
this.Configuration = configuration;
}
public string Src { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "img";
var CdnUrlBase = Configuration["CdnUrl"];
// make sure CndUrlBase endwith "/"
if (String.IsNullOrEmpty(CdnUrlBase)) { CdnUrlBase ="/"; }
if (!CdnUrlBase.EndsWith("/")) { CdnUrlBase = CdnUrlBase + "/"; }
// make sure src don't start with "/"
if (Src.StartsWith("/")) { Src= Src.Substring(0, Src.Length - 1); }
output.Attributes.SetAttribute("src", CdnUrlBase + Src);
}
}
after importing the CdnImgTagHelper into your _ViewsImports file , we can use it like this :
<cdn-img src="mfcpv.png"></cdn-img>
Since I've configured my appsettings.json with a
"CdnUrl": "https://i.stack.imgur.com"
the generated img looks like :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.