c# - Blazor:管理环境特定变量
问题描述
如何管理客户端 blazor 中不同环境的访问变量?通常,由于我使用 Azure 发布应用程序,我会使用该appsettings.json
文件进行本地应用程序设置,然后在我的应用程序服务的 Azure 应用程序设置部分设置条目,以获取本地环境和其他环境之间不同的条目。
我想要完成的一个例子:
客户端 Blazor:
@functions {
//...more code here
await Http.PostJsonAsync<object>("http://localhost:50466/api/auth/register", vm);
}
在部署的 Web 服务器上,这应该转换为:
@functions {
//...more code here
await Http.PostJsonAsync<object>("http://wwww.mywebsite.com/api/auth/register", vm);
}
因此,我正在寻找一种将站点根 url 存储在环境变量中并在发布时对其进行转换的方法。有没有一种 Blazor-ey 的方式来做到这一点?
解决方案
您可以使用配置界面创建单例并将其注入您的组件中。
.csproj
<ItemGroup>
<EmbeddedResource Include="appsettings.Development.json" Condition="'$(Configuration)' == 'Debug'">
<LogicalName>appsettings.json</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="appsettings.json" Condition="'$(Configuration)' == 'Release'">
<LogicalName>appsettings.json</LogicalName>
</EmbeddedResource>
</ItemGroup>
启动.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(GetConfiguration());
}
private IConfiguration GetConfiguration()
{
// Get the configuration from embedded dll.
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"))
using (var reader = new StreamReader(stream))
{
return JsonConvert.DeserializeObject<IConfiguration>(reader.ReadToEnd());
}
}
MyComponent.razor
@inject Configuration.IConfiguration Configuration;
或者看这个问题
推荐阅读
- flutter - Flutter FirebaseAuth:当电子邮件地址格式错误时,SignInWithEmailAndPassword 无法处理错误
- android - 按钮现在可以在 android studio 中使用运动布局
- api - 调用 api 并在 Nodejs 中返回这些值
- python - 如何改进 ML 模型以提高准确性
- java - Android AppUpdateManager 未初始化自动更新
- stenciljs - Stencil 组件未呈现更新的选项卡
- sql - 仅在其他 2 个日期字段之间显示日期字段
- macos - 在 MacOS 终端中获取当前月份的第一个日期
- php - Laravel 限制字符
- javascript - 以同步方式执行JS异步函数(特殊情况)