只需将其实现到我的项目中,我想我会分享我的代码。我创建了一个文本文件并将其存储在网站中,因此可以轻松修改它而无需重新编译或更改 web.config 设置。
执行此操作的一个好方法是在按钮提交上执行此操作,因为您使用的是 RTE。我会说使用 ajax 在按钮提交之前检查它是否包含“坏词”,这样您就不必进行回发,但看起来您正在使用 Win Forms,这就是 MVC。但是你可以得到图片。
我在这个网站https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words使用了英语和西班牙语的“坏词”
文本文件放在 /Content 文件夹中(在我的情况下)
这里是 ajax,如果你可以使用(或者如果其他人想要的话)
$('#form-ID').on('click', 'button[type="submit"]', function (e) {
var badWords = '',
str = $('#form-ID').find('textarea').val();
$.ajax({
url: '/YourAPI/CheckForBadWords?str=' + str,
type: 'POST',
dataType: 'json',
data: '',
async: false,
contentType: 'application/json; charset=utf-8',
complete: function (data) {
badWords = data.responseText;
}
});
if (badWords != '') {
console.log('oh no --- ' + badWords)
e.preventDefault();
return false;
}
});
Api 方法 - 您也可以将其放入您的 Button 提交事件中
[HttpPost] // <--- remove if not using Api
public string CheckForBadWords(string str)
{
string badWords = string.Empty;
var badWordsResult = Global.CheckForBadWords(str);
if (badWordsResult.Length > 0)
{
badWords = string.Join(", ", badWordsResult);
}
return badWords;
}
Global.cs 文件
public static class Global
{
/// <summary>
/// Returns a list of bad words found in the string based
/// on spanish and english "bad words"
/// </summary>
/// <param name="str">the string to check</param>
/// <returns>list of bad words found in string (if any)</returns>
public static string[] CheckForBadWords(string str)
{
var badWords = GetBadWords();
var badWordsCaught = new List<string>();
if (badWords.Any(str.ToLower().Contains))
{
badWordsCaught = badWords.Where(x => str.Contains(x)).ToList();
}
return badWordsCaught.ToArray();
}
/// <summary>
/// Retrieves a list of "bad words" from the text file. Words include
/// both spanish and english
/// </summary>
/// <returns>strings of bad words</returns>
private static List<string> GetBadWords()
{
var badWords = new List<string>();
string fileName = string.Format("{0}/Content/InvalidWords.txt", AppDomain.CurrentDomain.BaseDirectory);
if (System.IO.File.Exists(fileName))
{
badWords = System.IO.File.ReadAllLines(fileName).ToList();
}
return badWords.ConvertAll(x => x.ToLower());
}
}
编辑:
必须从 URL 字符限制的 api 调用 b/c 中删除查询字符串参数。相反,我只是传递 JSON 字符串
var badWords = '',
str = stringHERE;
$.ajax({
url: '/YourApiController/CheckForBadWords',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ str: str }),
async: false,
contentType: 'application/json; charset=utf-8',
complete: function (data) {
badWords = data.responseText;
}
});