I have a Blazor
browser-side project and i am trying to use a configuration json
file in order to set some things up.
I do not understand where to place this config file in order to use it later on.
So my folder structure is :
Folder schema when publishing
-root //tried placing the json here
- [Blazor server's dll's]
- Client
-dist //tried placing the json here
-framework/
-css/
-index.html
Client
public class Startup {
public static Config config;
public static Action<IServiceCollection> ConfigureServicesForDebugging { get; set; }
public void ConfigureServices(IServiceCollection services) {
ConfigureServicesForDebugging?.Invoke(services);
services.AddSingleton<AdminService>();
Console.WriteLine(Directory.GetCurrentDirectory()); //renders /
var config = File.ReadAllText("conf.json");
}
public void Configure(IBlazorApplicationBuilder app) {
app.AddComponent<App>("app");
}
}
I just want to be able to read that configuration file inside the Client
project and i do not know how.It can't find it.
I tried to print and see the Console.WriteLine(Directory.CurrentDirectory)
but i would get the relative path.
How can i find the current directory of my blazor application in order to retrieve the configuration for the Client project ?
Update
Usage
I have a couple of html forms where i bind some html attributes like the action
to some config file value:
class Config
{
public string FormUrl{get;set;}
}
Blazor Form
<form action=config.FormUrl>
<input type="submit">Submit</button>
</form>
@functions()
{
[Parameter] protected Config config{get;set;}
}
I assume i need to have this Config
resolved in the Startup
somehow.
It's not really about the 'where', all files are relative to wwwroot, like images etc.
But it is about how you read a file. File.ReadAllText() probably throws, it is not supported from a browser.
You can take a leaf from the /fetchdata sample page: use HttpClient.
I whipped up a sample but I couldn't get anything working in the Startup class. I guess that essential parts (like the HttpClient) are not configured yet.
So you can read the config from your main page, or implement it in App.razor :
@inject HttpClient Http
<Router AppAssembly="typeof(Program).Assembly">
<NotFoundContent>
<p>Sorry, there's nothing at this address.</p>
</NotFoundContent>
</Router>
@code
{
protected override async Task OnInitAsync()
{
string json = await Http.GetStringAsync("/conf.json");
Console.WriteLine(json);
}
}
this reads wwwroot/conf.json