简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM