“ &”字符将破坏存储在 web.config 中的密码

我有一个 ASP.NET MVC3 C # . NET 应用程序在 IIS 7.5上运行。

我们有一个 Windows NT 服务帐户,我们模拟在我们的代码,以便读/写文档到一个文件共享。用户 id 在代码中编译,服务帐户密码存储在 web.config 文件中。

密码包含一个与号字符(即: p&ssword)。

这破坏了网站。当访问站点时,我们收到这个错误: “对不起,在处理您的请求时发生了一个错误”。

下面是使用密码的代码:

    var password = ConfigurationManager.AppSettings.Get(Common.SVC_PWD);


bool isSuccess = LogonUser(
@"my_svc_acct",
"my.domain.net",
password,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token
);

为什么这会导致网站崩溃?

99025 次浏览

I suspect that you didn't encode the password properly in the web.config file. Remember that web.config is a XML file, so entities must be encoded.

Instead of

my&password

try

my&password

You can use sites such as FreeFormatter.com to escape/unescape XML strings.

You will need to put the encoded value in the web.config. It will read it out properly once you pull it but in the config file itself it needs to be encoded.

eg:

Password: your&password (what you expect)

Encoded version: your&password (what should be stored in your web.config)

Your wrapper method that reads out the value should unencode it automatically to your&password.

You will need to do this for all 'special' characters:

< = &lt;
> = &gt;
" = &quot;
' = &apos;
& = &amp;

store the password in the web.config using CDATA

replace the password with this

<![CDATA[MyPassw&rd]]>