【问题标题】:Understanding where to put config file in Blazor WASM了解在 Blazor WASM 中放置配置文件的位置
【发布时间】:2022-01-27 16:51:21
【问题描述】:

如果有人能指出我正确的方向,我将不胜感激。很抱歉,这篇文章很长,所以我很抱歉。

在我的旧 ASP.NET webforms 应用程序中,我有以下项目结构: 业务层 数据访问层 实用程序层 网页界面

WebUI 将具有以下项目依赖项 业务层 实用工具层

BusinessLayer 将具有以下项目依赖项 数据访问层 实用工具层

WebUI 会有一个包含数据库设置等的 web.config 文件。

现在在我的新 Blazor WASM 应用程序中,我有以下项目结构: API层 业务层 数据访问层 实用程序层 服务器.UI Wasm.UI

APILayer 将具有以下项目依赖项 BusinessLayer 并直接调用方法

Wasm.UI 将具有以下项目依赖项 UtilitiesLayer 并会调用 APILayer 来获取数据

Server.UI 将具有以下项目依赖项 UtilitiesLayer 并会调用 APILayer 来获取数据

BusinessLayer 将具有以下项目依赖项 数据访问层 实用工具层

现在我的问题是我应该将包含数据库设置的 appsettings.json 放在哪里。目前我在 UtilitiesLayer 中有一个名为 WebsiteSettings 的类,例如

public static string ThisDatabaseConnectionString { get; set; }

并在 MainLayout.razor 中设置我第一次运行应用程序时的设置

@inject IConfiguration configuration
UtilitiesLayer.WebsiteSettings.ThisDatabaseConnectionString = configuration.GetSection("ConnectionStrings").GetSection("ThisDatabaseConnectionString").Value;

"ConnectionStrings": {
    "ThisDatabaseConnectionString": "Server=127.0.0.1;Port=3306;Database=thisDB;Uid=root;Pwd=password;"
  },

如果我将项目依赖项直接放在 BusinessLayer 上,这一切正常,但因为我通过 APILayer 中的 HttpClient 调用 BusinessLayer,如下所示:

sUrl = "https://localhost:7263/DBAPIs/GetAllUser";

using (var http = new HttpClient())
{
    oDic = await http.GetFromJsonAsync<List<Users>>(sUrl);
}

在业务层中

DataTable dt = MySQLHelper.ExecuteDataTable(UtilitiesLayer.WebsiteSettings.ThisDatabaseConnectionString, sqlCommand);

UtilitiesLayer.WebsiteSettings.ThisDatabaseConnectionString 始终为空。

那么我在哪里可以放置我可以在所有项目中始终访问 UtilitiesLayer.WebsiteSettings.ThisDatabaseConnectionString 的设置文件?

【问题讨论】:

标签: blazor


【解决方案1】:

您可以使用 sharedsettings.json 配置文件,该配置文件可以跨项目共享。您可以通过以下方法加载共享设置

  .ConfigureAppConfiguration((hostingContext, config) =>
{
  var env = hostingContext.HostingEnvironment;

   var sharedFolder = Path.Combine(env.ContentRootPath, "..", "Shared");

config
    .AddJsonFile(Path.Combine(sharedFolder, "SharedSettings.json"), optional: true) // When running using dotnet run
    .AddJsonFile("SharedSettings.json", optional: true) // When app is published
    .AddJsonFile("appsettings.json", optional: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

config.AddEnvironmentVariables();
})

具体实现请使用以下链接

https://andrewlock.net/sharing-appsettings-json-configuration-files-between-projects-in-asp-net-core/

【讨论】:

  • 非常感谢您的回复。我会对此进行调查并回复您:) 感谢您抽出宝贵的时间回复我的帖子
猜你喜欢
  • 2019-12-08
  • 2021-12-27
  • 2020-11-19
  • 2020-07-27
  • 2011-01-15
  • 2013-12-26
  • 2020-10-16
  • 2020-04-25
  • 1970-01-01
相关资源
最近更新 更多