【发布时间】:2010-12-22 09:50:18
【问题描述】:
如何确定字符串是否已在 C# 中以编程方式编码?
让例如字符串:
<p>test</p>
我想让我的逻辑理解它已被编码的这个值.. 有任何想法吗?谢谢
【问题讨论】:
如何确定字符串是否已在 C# 中以编程方式编码?
让例如字符串:
<p>test</p>
我想让我的逻辑理解它已被编码的这个值.. 有任何想法吗?谢谢
【问题讨论】:
您可以使用HttpUtility.HtmlDecode() 对字符串进行解码,然后将结果与原始字符串进行比较。如果它们不同,则可能是对原始字符串进行了编码(至少,例程在内部找到了要解码的内容):
public bool IsHtmlEncoded(string text)
{
return (HttpUtility.HtmlDecode(text) != text);
}
【讨论】:
IsHtmlEncoded("&lt;p&gt;test&lt;/p&gt;") 应该给true,所以它被编码了。
"><script>alert('XSS');</script>&amp;,那么它将解码&amp;,字符串将不匹配,它会被视为已编码。
严格来说这是不可能的。字符串包含的实际上可能是预期的文本,其编码版本将是&amp;lt;p&amp;gt;test&amp;lt;/p&amp;gt;。
您可以在字符串中查找 HTML 实体,并对其进行解码,直到没有剩余,但以这种方式解码数据是有风险的,因为它假设的事情可能不正确。
【讨论】:
这是我的看法...如果用户传入部分编码的文本,这将捕获它。
private bool EncodeText(string val)
{
string decodedText = HttpUtility.HtmlDecode(val);
string encodedText = HttpUtility.HtmlEncode(decodedText);
return encodedText.Equals(val, StringComparison.OrdinalIgnoreCase);
}
【讨论】:
我使用下面的NeedsEncoding() 方法来确定字符串是否需要编码。
Results
-----------------------------------------------------
b --> NeedsEncoding = True
<b> --> NeedsEncoding = True
<b> --> NeedsEncoding = True
<b< --> NeedsEncoding = False
" --> NeedsEncoding = False
这里是辅助方法,为了清楚起见,我将其分为两种方法。像Guffa says 一样,它是有风险的,很难产生防弹方法。
public static bool IsEncoded(string text)
{
// below fixes false positive <<>
// you could add a complete blacklist,
// but these are the ones that cause HTML injection issues
if (text.Contains("<")) return false;
if (text.Contains(">")) return false;
if (text.Contains("\"")) return false;
if (text.Contains("'")) return false;
if (text.Contains("script")) return false;
// if decoded string == original string, it is already encoded
return (System.Web.HttpUtility.HtmlDecode(text) != text);
}
public static bool NeedsEncoding(string text)
{
return !IsEncoded(text);
}
【讨论】:
检测这种情况的一种简单方法是检查编码字符串中不允许出现的字符,例如 。
【讨论】:
我只能建议你用解码后的字符串替换已知的编码部分。
replace("<", "<")
【讨论】:
我正在进行 .NET Core 2.0 开发,并且正在使用 System.Net.WebUtility.HtmlDecode,但我遇到的情况是,在微服务中处理的字符串可能对某些字符串执行的编码数量不确定。所以我整理了一个小递归方法来处理这个问题:
public string HtmlDecodeText(string value, int decodingCount = 0)
{
// If decoded text equals the original text, then we know decoding is done;
// Don't go past 4 levels of decoding to prevent possible stack overflow,
// and because we don't have a valid use case for that level of multi-decoding.
if (decodingCount < 0)
{
decodingCount = 1;
}
if (decodingCount >= 4)
{
return value;
}
var decodedText = WebUtility.HtmlDecode(value);
if (decodedText.Equals(value, StringComparison.OrdinalIgnoreCase))
{
return value;
}
return HtmlDecodeText(decodedText, ++decodingCount);
}
在这里,我在字符串被编码的列表中的每个项目上调用了该方法:
result.FavoritesData.folderMap.ToList().ForEach(x => x.Name = HtmlDecodeText(x.Name));
【讨论】:
试试这个答案:Determine a string's encoding in C#
另一个代码项目可能会有所帮助.. http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
您也可以使用正则表达式来匹配字符串内容...
【讨论】: