如何在连接字符串中包含&符号? [英] How to include ampersand in connection string?
问题描述
我将 Entity Framework 4 用于一个简单的应用程序,并希望将我的连接凭据烘焙到以下连接字符串中:
I'm using Entity Framework 4 for a simple app and would like to bake my connection credentials into the following connection string:
<connectionStrings>
<add name="MyEntities"
connectionString="metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhostDEV;Initial Catalog=MyDB;UserId=myUser;Password=jack&jill;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
但是,密码(我无法更改)包含一个和号.ASP.NET 抛出:配置错误:解析 EntityName 时出错.第 XX 行,位置 YYY.
However, the password (which I cannot change) contains an ampersand. ASP.NET throws:
Configuration Error: An error occurred while parsing EntityName. Line XX, position YYY.
如果我用 &
替换密码中的 & 符号,我会得到一个 SqlException: Login failed for user 'myUser'.
通常这个技巧有效,但是我猜有什么地方出问题了,因为这在技术上是连接字符串中的一个连接字符串.
If I replace the ampersand in the password with &
, I get a SqlException: Login failed for user 'myUser'.
Usually this trick works, but I'm guessing that something is failing because this is technically a connection string inside a connection string.
我应该在这里做什么?我的大部分课程都包含以下代码:
What should I do here? Most of my classes include code like:
using (var context = new MyEntities()) {
// do work
}
<小时>
更新: 事实证明我使用的凭据是域帐户,所以我真正需要的是连接字符串中的 Integrated Security=True
而不是密码.
Update: It turns out that the credentials I am using are a domain account, so what I really need is Integrated Security=True
in the connection string rather than a password.
按照接受的答案中的指示对 & 符号进行编码应该工作正常,尽管我还没有测试过.
Encoding the ampersand as indicated in the accepted answer should work fine, though I haven't tested it.
推荐答案
您需要像处理任何 XML 文档一样使用转义序列,这是所有 .config 文件.
You'll need to use escape sequences like you would for any XML document, which is all the .config files are.
- 与号 = &=
&
- 大于 = > =
>
- 小于 = <=
<
- 撇号 = ' =
'
- 引用 = " =
"
你也可以使用CDATA
标签,这样你就可以使用这些非法字符了
You can also use the CDATA
tag so that you can use these illegal characters
并以
]] 结尾>
<connectionStrings>
<add name="MyEntities" connectionString="
metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=localhostDEV;
Initial Catalog=MyDB;UserId=myUser;
Password=<![CDATA[jack&jill]]>;
MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
这篇关于如何在连接字符串中包含&符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!