我们有ServiceStack请求:
MyRequest{
public string Name {get;set;}
}
默认情况下我需要拒绝所有请求中的所有html,并且仅当我有[AllowHtml]属性时才允许html。就像在MVC中一样。
MyRequest{
[AllowHtml]
public string Name {get;set;}
}
ServiceStack可以吗?
答案 0 :(得分:1)
我们是如何做到的: 1.添加用于检查HTML的插件
public class SecurityValidationFeature : IPlugin
{
private readonly ISecurityValidator[] _validators;
public SecurityValidationFeature(ISecurityValidator[] validators)
{
_validators = validators;
}
2。 DTO的接口方法:
public virtual Dictionary<string, string> StringFieldsAsEnum
{
get
{
return new Dictionary<string, FieldValue>()
{
{"Name", new FieldValue(this.Name, AllowHtml)},
{"Fio", new FieldValue(this.Fio, AllowHtml)},
{"Email", new FieldValue(this.Email, AllowHtml)},
{"Post", new FieldValue(this.Post, AllowHtml)}
};
}
}
3。最后检查验证器:
public void Validate(Dictionary<string, FieldValue> fields)
{
if (fields == null || fields.Count == 0)
return;
Dictionary<string, string> failed = new Dictionary<string, string>();
foreach (var field in fields)
{
if (string.IsNullOrEmpty(field.Value.Value))
continue;
if (IsXssInjectible(field.Value))
{
failed.Add(field.Key, field.Value.Value);
}
}
if (failed.Count > 0)
throw new XssException(failed);
}
private bool IsXssInjectible(Field field)
{
return !field.AllowHtml && HasHtmlTags(field.Value);
}
private bool HasHtmlTags(string input)
{
return Regex.IsMatch(input, "<.*?>"); //проверяем любые закрытые теги
}