Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to acess the appsettings in blazor webassembly

I currentying trying to save the api url in an appsettings. However, the configuration.Propertiers seems to be empty. I am not sure how to get the setting. in program.cs:

public static async Task Main(string[] args)
{
   var builder = WebAssemblyHostBuilder.CreateDefault(args);
   //string url = builder.Configuration.Properties["APIURL"].ToString();
   foreach (var prop in builder.Configuration.Properties)
      Console.WriteLine($"{prop.Key} : {prop.Value}" );
   //builder.Services.AddSingleton<Service>(new Service(url));
   builder.RootComponents.Add<App>("app");
   await builder.Build().RunAsync();
}
like image 677
Zo. Avatar asked Mar 05 '20 19:03

Zo.


People also ask

How do you use session in Blazor WebAssembly?

localStorage and sessionStorage can be used in Blazor WebAssembly apps but only by writing custom code or using a third-party package. Generally, sessionStorage is safer to use. sessionStorage avoids the risk that a user opens multiple tabs and encounters the following: Bugs in state storage across tabs.

How do I read a JSON file in Blazor?

Use the HttpClient class with the GetFromJsonAsync() method to read a JSON file in Blazor WebAssembly. Follow these steps to read the JSON file. Create or load a JSON file under the wwwroot folder.

How do I run Blazor WebAssembly app from command line?

Open a command prompt where you want your project to be located and run the following command. Run the cd BlazorServerApp command to navigate to the BlazorServerApp folder. Run the apllication. The dotnet run command runs the application.

How do you get Blazor WebAssembly?

Getting started with Blazor WebAssembly is easy: simply go to https://blazor.net and install the latest . NET Core SDK (3.1. 300 or later), which includes everything you need to build and run Blazor WebAssembly apps. Browse to https://localhost:5001 and voilà!


2 Answers

Inkkiller nailed it. You can simplify the call into IConfiguration without the APIHelper class and access it directly in Program.cs from the WebAssemblyHostBuilder.

appsettings:

{
   "ServerlessBaseURI": "http://localhost:0000/",
}

Program.cs:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}


like image 53
hubris Avatar answered Oct 03 '22 17:10

hubris


This answer concerned blazor preview when blazor didn't support appsettings.json in wwwroot folder yet. You should use appsettings.json in wwroot folder now and WebAssemblyHostBuilder.Configuration. It also support per environment files (appsettings.{env}.Json).

I solve this issue by using a settings.json file store in the app wwwroot folder and register a task to get the settings :

Settings.cs

public class Settings
{
    public string ApiUrl { get; set; }
}

wwwroot/settings.json

{
   "ApiUrl": "https://localhost:51443/api"
}

Progam.cs

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    builder.Services.AddSingleton(async p =>
    {
        var httpClient = p.GetRequiredService<HttpClient>();
        return await httpClient.GetJsonAsync<Settings>("settings.json")
            .ConfigureAwait(false);
    });

SampleComponent.razor

@inject Task<Settings> getsettingsTask
@inject HttpClient client
...
@code {
    private async Task CallApi()
    {
        var settings = await getsettingsTask();
        var response = await client.GetJsonAsync<SomeResult>(settings.ApiUrl);
    }
}

This has advantages:

  • Doesn't share the server's appsettings.json file which can be a security hole
  • Configurable per environment
like image 45
agua from mars Avatar answered Oct 03 '22 18:10

agua from mars