我创建了一个对电子邮件地址进行编码的 Html 助手,以防止垃圾邮件。这与 MarkdownSharp 库在自动生成电子邮件链接时使用的技术相同。
问题是对TagBuilder.MergeAttribute
破坏链接的属性文本进行编码。是否可以覆盖此行为或至少以另一种方式指定属性。我知道我可以回退到仅使用字符串连接或 aStringBuilder
但TabBuilder
确实提供了许多好处,例如轻松合并其他 HTML 属性。
/// <summary>
/// Creates an encoded email link in the hopes of foiling most SPAM bots
/// </summary>
public static IHtmlString EmailLink(this HtmlHelper html, string email, string text = null, object htmlAttributes = null)
{
Ensure.Argument.NotNullOrEmpty(email, "email");
var encodedEmail = EncodeEmailAddress(email);
var tb = new TagBuilder("a");
tb.MergeAttribute("href", "mailto:" + encodedEmail);
tb.InnerHtml = text ?? encodedEmail;
if (htmlAttributes != null)
{
tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
}
return new HtmlString(tb.ToString());
}
/// <summary>
/// encodes email address randomly
/// roughly 10% raw, 45% hex, 45% dec
/// note that @ is always encoded and : never is
/// </summary>
private static string EncodeEmailAddress(string addr)
{
var sb = new StringBuilder(addr.Length * 5);
var rand = new Random();
int r;
foreach (char c in addr)
{
r = rand.Next(1, 100);
if ((r > 90 || c == ':') && c != '@')
sb.Append(c); // m
else if (r < 45)
sb.AppendFormat("&#x{0:x};", (int)c); // m
else
sb.AppendFormat("&#{0};", (int)c); // m
}
return sb.ToString();
}