Format arguments as json in script block

We’re creating a new custom Auth API with a sign-on dialog created in Vue. We’re serving it up via the FallbackRoute and we’ve enabled SharpPagesFeature and we’re passing in a few arguments for testing.

public object Any(FallbackForClientRoutes request) => 
	new PageResult(Request.GetPage("/"))
	{
		Args =
		{
			["AppName"] = "MyStory",
			["SupportUrl"] = "https://example.com/support",
			["LogoutUrl"] = "https://example.com/logout",
			["MyStoryUrl"] = _appSettings.GetString("MyStoryUrl")
		},
	};

We’d like to pass these arguments into the Vue instance by creating a script block with the arguments formatted as json so that on initialization the Vue app can read the json object as detailed in https://codeburst.io/passing-configuration-to-vue-js-1b96fa8f959

Is there a way to format Args as json, or can I create a context object and have that formatted as json and have it properly encoded within the html?

Use the json method in your _layout.html page, e.g:

<script>CONFIG = {{ {AppName,SupportUrl,LogoutUrl,MyStoryUrl} |> json }}</script>

Then you can access it as a global variable. Since it’s global in node.js I prefer to also use it in my scripts by assigning it as an alias for the DOM’s window object, e.g:

<script>var global=window</script>

Which I’ll reference in my scripts instead. As I use TypeScript I have to declare it as an external variable, then I can access it as normal.

declare let global: any;

const config = global.CONFIG as any;

Note: json uses camelCase by default in ASP .NET Core which you’ll need to use in .js instead