在 MVC 中更改 web.config 处的连接字符串

Changing connection string at web.config in MVC

我首先使用 MVC 数据库设置了一个 MySQL 连接字符串,如下所示:

<add name="wf_workflowEntities" connectionString="metadata=res://*/Models.MySql.Model1.csdl|res://*/Models.MySql.Model1.ssdl|res://*/Models.MySql.Model1.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=192.168.1.8;user id=test;password=abc.1234;CHARSET=utf8;database=wf_workflow&quot;" providerName="System.Data.EntityClient" /> 

如果是needed.for实例,我想替换连接字符串的一些参数,为了切换服务器,必须重新设置服务器的IP(例如用户名,密码)。

我使用这个模型发送自定义参数:

public partial class BPMEngine
{
    public string DBServer { get; set; }//ip server
    public string DBName { get; set; }//database name
    public string DBUserName { get; set; }//username
    public string DBPass { get; set; }//password
}

这是视图:

@Html.TextBoxFor(model => model.DBServer, new { @class = "form-control1", placeholder = "ip server" })
@Html.TextBoxFor(model => model.DBName, new { @class = "form-control1", placeholder = "database name" })
@Html.TextBoxFor(model => model.DBUserName, new { @class = "form-control1", placeholder = "username" })
@Html.TextBoxFor(model => model.DBPass, new { @class = "form-control1", placeholder = "password" })
<button type="submit" class="btn btn-block btn-success"  id="transfer">save</button>

但我不知道如何通过控制器(或操作结果)更改 web.config 处的连接字符串参数。

其实我也不知道,这个问题在controller里应该怎么办?

您可以使用方法 supplied here 在运行时更改连接。

// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
(
    initialCatalog: "name-of-another-initialcatalog",
    userId: "jackthelady",
    password: "nomoresecrets",
    dataSource: @".\sqlexpress" // could be ip address 120.273.435.167 etc
);

我认为这是完成您需要的更好方法,处理程序化 web.config 修改可能很麻烦,但是,如果您更喜欢 web.config 修改路线,您可以使用 this another one.

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = 
  (ConnectionStringsSection)configuration.GetSection("connectionStrings");
  section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();