Home > Software design >  How do you inject your appsettings.json configuration in a razor page C# code block?
How do you inject your appsettings.json configuration in a razor page C# code block?

Time:12-12

I was following the following official documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#access-configuration-in-razor-pages

This implementation of @Configuration["myKey"] works perfectly for code that is not in between @{} brackets, but when I have a code block it simply does not work.

The documentation provides no code examples as far as I can see...

How do I solve this problem?

The code is of course in a Razor page (.cshtml).

I tried removing the @ and putting in the same code without the @, but then it gives a context error...

P.S. the code in question is a POCO if it matters.

P.P.S. I use @inject IConfiguration Configuration for importing the configuration at the top of the Razor page.

My problematic code:

var website = new WebSite()
        {
    private string altName = Configuration["FrameworkData:PageTitle"]  " - "  Configuration["FrameworkData:Slogan"];
    AlternateName = altName,
....

I've already tried specifying the IConfiguration Type before the Configuration specification without any avail.

UPDATE

My starting code with the problematic parts in it:

@using Microsoft.AspNetCore.Http;
@using Schema.NET;
@model projectname2.Areas.MyFeature.Pages.Shared._LayoutModel
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@{  
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name='description' content='@ViewData["Description"]'>
    <title>@ViewData["Title"] - @Configuration["FrameworkData:PageTitle"]</title>
    @{
        var website = new WebSite()
        {
            private string altName = "";
    string altName = $"{Configuration["FrameworkData:PageTitle"]} - {Configuration["FrameworkData:Slogan"]}";
    AlternateName = altName,
    Name = Configuration["FrameworkData:PageTitle"],
    Url = new Uri("https://example.com")
};
        var jsonLd = website.ToString();
        var address = new PostalAddress()
        {
        StreetAddress = "Example street 10",
        AddressLocality = "NY",
        PostalCode = "11111",
        AddressCountry = "US"
        };
        var geo = new GeoCoordinates()
        {
            Latitude = 0.3947623,
            Longitude = 0.8723408
        };
        var localbusiness = new LocalBusiness()
            {
                Name = "Project name",
                Image = new Uri("https://example.com/graphics/logo.svg"),
                Url = new Uri("https://example.com"),
                Telephone = "1234 1243567",
                Address = address,
                Geo = geo,
                SameAs = new Uri("https://example.com"),
                OpeningHours = "Mo-Fr 08:00-17:00",
            };
        
        var jsonLdlb = localbusiness.ToString();
        var organization = new Organization()
            {
                AreaServed = "US",
                ContactPoint = new ContactPoint()
                {
                    AvailableLanguage = "English",
                    ContactOption = ContactPointOption.TollFree,
                    ContactType = "customer service",
                    Telephone = "1234 1243567"
                },
                Url = new Uri("https://example.com"),
                Logo = new Uri("https://example.com/graphics/logo.svg"),
            };
            var jsonLdorg = organization.ToString();
    }
<script type="application/ld json">
    @Html.Raw(jsonLd)
</script>
<script type="application/ld json">
    @Html.Raw(jsonLdlb)
</script>
<script type="application/ld json">
    @Html.Raw(jsonLdorg)
</script>

CodePudding user response:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@{
   string myValue = Configuration["FrameworkData:PageTitle"];
   // Do your things
}

Refer Microsoft Docs

CodePudding user response:

I had to define the variables outside of the problematic code block in an another code block like this:

@{
    var pageTitle = Configuration["FrameworkData:PageTitle"];
}

I had to define the altName before initializing the WebSite() instance:

var altName = $"{pageTitle} - {slogan}";
var website = new WebSite()

And then I can just reference the variable by variable name.

Case closed.

  • Related