Annas
Annas

Reputation: 161

Asp.Net core razor - how to use appsettings.json value in _Layout.cshtml file?

In ASP.NET Core with Razor Pages solution, I have an appsettings.development.json file like below.

I want to get the value of APP_ID from the appsettings.development.json file in _Layout.cshtml file. How to do this?

I have tried like below, it shows console error in browser - "Uncaught SyntaxError: missing ) after argument list". Please let me know how to use this value from the json file:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        console.log('from settings ' + @Configuration["APP_ID"]);

…

My appsettings.development.json file:

{
  "APP_ID" : "xxxxxxxxxx",
  "APP_Value" : "zzzzzzzzzzzzz"
}

Upvotes: 0

Views: 5040

Answers (1)

poke
poke

Reputation: 388013

console.log('from settings ' + @Configuration["APP_ID"]);

You have to keep in mind that rendering something on the server using Razor has nothing to do with how that is being interpreted in the browser.

When Razor renders the above, it will write the following to the result (when APP_ID = "xxxxxxxxxx"):

console.log('from settings ' + xxxxxxxxxx);

As you can see, there is now the value of your APP_ID written directly inside the console.log call. Razor does not know what it is writing though so this is how it will produce the output.

Then, when this is being received and executed by the browser, the browser will see that + xxxxxxxxxx part which, depending on the actual value, will fail with one of many possible errors. Because from the JavaScript view point, this is invalid.

So in order to fix this, you will have to make sure that your Razor view produces valid code for the browser. This applies to both JavaScript and HTML too. One way to do this is to use the JSON serializer that is available within Razor views. Since JSON is the JavaScript notation, it will always be valid JavaScript, so you can use this well for passing data from Razor to JavaScript.

In your case, you could write it like this:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        console.log('from settings ' + @Json.Serialize(Configuration["APP_ID"]));

…

Note the Json.Serialize call around your value. When the JSON serializer receives just a string, it will properly enquote it – and also take care of properly escaping any quote within the value itself. So this is a very safe way to embed your value into JavaScript.

Upvotes: 1

Related Questions