Update because Blazor got more complete:
By now, Blazor actually has the config-process we're used to from other .NET Applications, just a litte more...frontend-y:
You create an appsettings.json
file for special configurations, like appsettings.Release.json
. For Blazor you have to put it into the wwwroot
folder.
The file should look something like this:
{
"BaseUrl": "https://localhost:12345"
}
And in your appsettings.Release.json, you would put your prod url instead of localhost.
You can now go into your Program.cs and read the settings like this:
baseAddress = builder.Configuration.GetValue<string>("BaseUrl");
builder.Services.AddSingleton(new HttpClient
{
BaseAddress = new Uri(baseAddress) }
);
Now all your class constructed automatically, like components, can use DI to get the configured HttpClient. You just put this at the top:
@inject HttpClient Http
And then use it from there. Of course use the DI scope of your choosing here (Transient/Scoped/Singleton).
Or, you know, just save the baseAddress somewhere if you don't wanna use DI.
This comes with preview-5, but we're even further by now with RC-1
Blazor is in production now, no need to play around with preview versions anymore.
Old answer:
As far as I know there isn't a "good" way of getting the environment yet, but since it's only about prod vs dev, you can do hte same as me and just use compiler variables old school style:
public class Program
{
internal const string BaseAddress = "http://localhost:81/";
internal const string ProdBaseAddress = "http://localhost:5001/";
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
var host = builder.Build();
var httpClient = host.Services.GetRequiredService<HttpClient>();
#if DEBUG
httpClient.BaseAddress = new Uri(BaseAddress);
#else
httpClient.BaseAddress = new Uri(ProdBaseAddress);
#endif
Console.WriteLine($"Set BaseAddress: {BaseAddress}");
await host.RunAsync();
}
}
Just make sure the DEBUG variable is actually set in your Debug build - mine was not.
Edit: Forgot the point: Locally you're likely using 'Debug' config, while when deploying you probably have a different config, like 'Release'.