How to use |DataDirectory| substitution string in appsettings.json with asp.net core?

孤者浪人 提交于 2021-01-28 12:40:24

问题


I'm new to asp.net core and the task I want to do should be very simple. Using Visual Studio, I'm trying to link a .mdf file to my project as a local database. As I want to make it work for several computers, I need to find the data directory folder path from appsettings.json. Therefore, after some researches, the best way to do that is using the |DataDirectory| substitution string.

The problem is that my website can't reach my mdf file this way and it generates an ArgumentException : "Invalid value for key 'attachdbfilename'". Although I found some topics about this issue, none of these answered to my question.

I've already tried to use the full path to find my file and it worked but as I said, I need to find it from several computers.

Here are Startup.cs and appsettings.json

Startup.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);
        }
        [...]
   }

My connection string, in appsettings.json :

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=|DataDirectory|\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

If needed, I can also provide the stack trace.

Thank you in advance for your help.


回答1:


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.



来源:https://stackoverflow.com/questions/55955282/how-to-use-datadirectory-substitution-string-in-appsettings-json-with-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!