c# - 转义和取消转义无效字符

标签 c# security escaping

这应该很容易。我有一个转义字符串,如下所示:

string originalString = "M&M";
string escapedString = System.Security.SecurityElement.Escape(originalString);//M&M

到目前为止还不错

string unEscapedString = System.Security.SecurityElement.FromString(escapedString).Text;

期望返回 M&M,但收到“对象未设置”

假设字符串应该是 xml 格式,所以在这种情况下我应该做什么的任何帮助都会有所帮助。

最佳答案

您可以使用System.Net.WebUtility类的静态 HtmlDecode方法:

string original = "M&M";
string escaped = System.Security.SecurityElement.Escape(original);
string unescaped = System.Net.WebUtility.HtmlDecode(escaped);
<小时/>

代码无法正常工作的原因是 FromString 方法需要有效的 xml。请参阅文档 here :

Parameters
xml String
The XML-encoded string from which to create the security element.

如果您在字符串周围添加 xml 标签,则可以使代码示例正常工作:

string unescaped = SecurityElement.FromString($"<x>{escaped}</x>").Text;

关于c# - 转义和取消转义无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59296318/

相关文章:

c# - 如何从 sourcecode.c 创建 DLL 库,然后在 C# 中使用它

security - Laravel 4 : how to protect assets folder?

java - java.security.cert.Certificate 中的验证方法是线程安全的吗?

java - 替换android中的字符串?

java - 使用 JdbcTemplate 时转义单引号

c# - : myType. GetType() 和 typeof(MyType) 哪个更有效?

c# - 从外部(C#)访问 while 循环内的变量?

c# - Powershell脚本错误 "Cannot find an overload for "LoadFromCollection“和参数计数: "1".”

security - 如果密码是用 "salt"加密的,如何在数据库中检查密码?

Django 。在引号内使用 url 标签,在引号内