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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14607920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:25:15  来源:igfitidea点击:

The "&" character breaks passwords that are stored in the web.config

c#asp.net.netasp.net-mvcconfiguration

提问by MikeTWebb

I have an ASP.NET MVC3 C# .NET Application running on IIS 7.5.

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

We have a Windows NT service account we Impersonate in our code in order to read/write documents to a file share. The user id is compiled in the code and the service account password is stored in the web.config file.

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

The password contains an ampersand character (i.e.: p&ssword).

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

This broke the site. When accessing the site we received this error :"Sorry, an error occurred while processing your request".

这破坏了网站。访问网站时,我们收到此错误:“抱歉,处理您的请求时出错”。

Here is the code that uses the password:

这是使用密码的代码:

    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
    );

Why would this cause the site to break?

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

采纳答案by Rui Jarimba

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

我怀疑您没有在web.config文件中正确编码密码。请记住,这web.config是一个 XML 文件,因此必须对实体进行编码。

Instead of

代替

my&password 

try

尝试

my&password

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

您可以使用诸如FreeFormatter.com 之类的站点来转义/取消转义 XML 字符串。

回答by Kelsey

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.

您需要将编码值放在 web.config 中。一旦你把它拉出来,它就会正确地读出它,但在配置文件本身中它需要被编码。

eg:

例如:

Password: your&password(what you expect)

密码:(your&password你所期望的)

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

编码版本:(your&password什么应该存储在你的 web.config 中)

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

读出值的包装器方法应自动将其解编码为your&password.

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

您需要对所有“特殊”字符执行此操作:

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

回答by Scott Selby

store the password in the web.config using CDATA

使用 CDATA 将密码存储在 web.config 中

replace the password with this

用这个替换密码

<![CDATA[MyPassw&rd]]>