c# - 如何使用 |数据目录| 用asp.net核心替换appsettings.json中的字符串?
问题描述
我是 asp.net core 的新手,我想做的任务应该很简单。使用 Visual Studio,我正在尝试将 .mdf 文件作为本地数据库链接到我的项目。由于我想让它适用于多台计算机,我需要从 appsettings.json 中找到数据目录文件夹路径。因此,经过一些研究,最好的方法是使用|DataDirectory| 替换字符串。
问题是我的网站无法通过这种方式访问我的 mdf 文件,它会生成 ArgumentException : "Invalid value for key 'attachdbfilename'"。虽然我找到了一些关于这个问题的话题,但这些话题都没有回答我的问题。
我已经尝试使用完整路径来查找我的文件并且它有效,但正如我所说,我需要从几台计算机中找到它。
这里是 Startup.cs 和 appsettings.json
启动.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "App_Data");
AppDomain.CurrentDomain.SetData("DataDirectory", path);
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
[...]
}
我的连接字符串,在appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=|DataDirectory|\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
},
如果需要,我还可以提供堆栈跟踪。
预先感谢您的帮助。
解决方案
Well, if someone still has the same issue as I had, I just found a solution :
You can simply replace the occurence of a string, with the path of your data folder.
Startup.cs :
string path = Path.Combine(Directory.GetCurrentDirectory(), "App_Data");
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection").Replace("[DataDirectory]", path)));
services.AddDefaultIdentity<IdentityUser>()
appsettings.json
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=[DataDirectory]\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
I replaced |DataDirectory| with [DataDirectory] to avoid program confusion with the substitution string. But if someone has a better explanation than me, it would be nice to do it.
推荐阅读
- javascript - 将 Json 数据映射到新的键值对 JavaScript 对象
- c++ - 如何使用 string::replace 方法写入文件?
- python - Match all identifiers in a string
- shopify - 推出新的 Shopify 主题和最佳方法
- r - 使用 R 闪亮的应用程序创建箱线图的问题
- gitlab-ci - 赛普拉斯测试后 Gitlab-ci 运行程序挂起
- kubernetes - kubernetes azure 节点超过最大卷数
- reactjs - 如何使用我的后端中使用的前端反应中的 Auth0 访问令牌
- android - 从 Listwiew 回到 MainActivity
- excel - 在 Excel 和 Word 中的 VBA 代码之间传递变量