我正在开发具有 Core 2.0 知识的 webapi
我需要创建两个链接以从不同的数据库产生不同的结果,两个数据库模式都相同。

喜欢 https://localhost:5000/m/University
https://localhost:5000/v/University
它们都在具有相同 webapi 应用程序的不同数据库中触发并给出结果。我可以产生结果,但我必须在启动类中创建两个 webapi 项目或更改连接字符串(“MConn”)。

  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(options => { options.AutomaticAuthentication = true; });
        services.AddDbContext<PIDBContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("MConn")));
        services.AddMvc();
    }

您能帮我如何根据 Https 请求使用具有不同连接字符串的相同 Webapi 项目吗?

谢谢

最佳答案

找到了解决办法:

  • 创建 DbContextFactory
    public static class DbContextFactory
    {
        public static Dictionary<string, string> ConnectionStrings { get; set; }
    
        public static void SetConnectionString(Dictionary<string, string> connStrs)
        {
            ConnectionStrings = connStrs;
        }
    
        public static AppContext Create(string connid)
        {
            if (!string.IsNullOrEmpty(connid))
            {
                var connStr = ConnectionStrings[connid];
                var optionsBuilder = new DbContextOptionsBuilder<AppContext >();
                optionsBuilder.UseSqlServer(connStr);
                var db = new AppContext (optionsBuilder.Options);
                return db;
            }
            else
            {
                throw new ArgumentNullException("Connection failed becuase of no Connection ID");
            }
       }
    }
    
  • 项目 Json 文件:
    {
        "ConnectionStrings": {
        "Sample1con": "your 1st connection string",
        "Sample2con": "your 2nd connection string"
        }
    }
    
  • 在 Startup 类的 Configure 方法中声明字典
    Dictionary<string, string> connStrs = new Dictionary<string, string>();
    connStrs.Add("p", Configuration.GetConnectionString("Sample1con"));
    connStrs.Add("m", Configuration.GetConnectionString("Sample2con"));
    DbContextFactory.SetConnectionString(connStrs);
    
  • 实际使用
    var _context = DbContextFactory.Create(db); ///Db would be your URL string.
    
  • 关于c# - WebAPI Core 2 具有相同上下文的多个连接字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47578544/

    10-12 00:13
    查看更多