csharp NotAllowedHtml.cs是一个数据注释addi
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp NotAllowedHtml.cs是一个数据注释addi相关的知识,希望对你有一定的参考价值。
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
namespace CommonFunctions.Validation
{
public class NotAllowedHtml : ValidationAttribute
{
#region properties
public bool ShowExceptionDetailsInValidationResult { get; set; }
public string ValidationFailureMessage { get; set; }
#endregion
#region Constructors
public NotAllowedHtml() : this("", false) { }
public NotAllowedHtml(string message) : this(message, false) { }
public NotAllowedHtml(string message, bool returnExceptionDetails)
{
ShowExceptionDetailsInValidationResult = returnExceptionDetails;
ValidationFailureMessage = message;
}
#endregion
public bool IsInvalidInput(string input)
{
var isValidInput = !ContainsOpenAndCloseTags(input); // check 1
if (isValidInput) isValidInput = !ContainsTag(input); // check 2
if (isValidInput) isValidInput = !ContainsTags(input); // check 3
if (!isValidInput) isValidInput = (input != HttpUtility.HtmlEncode(input)); // check 4
return isValidInput;
}
private static bool ContainsOpenAndCloseTags(string input)
{
XElement x = XElement.Parse("<wrapper>" + input + "</wrapper>");
bool isInvalidInput =
!(x.DescendantNodes().Count() == 1 && x.DescendantNodes().First().NodeType == XmlNodeType.Text);
return isInvalidInput;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
if (!IsInvalidInput(value.ToString()))
return ValidationResult.Success;
if (string.IsNullOrEmpty(ValidationFailureMessage))
ValidationFailureMessage = "Error - string contains HTML";
}
catch (Exception ex)
{
if (ShowExceptionDetailsInValidationResult)
return new ValidationResult(ex.ToString());
ValidationFailureMessage = "Error";
}
return new ValidationResult(ValidationFailureMessage);
}
protected static bool ContainsTags (string input)
{
const string regexString = @"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>";
return Regex.IsMatch(input, regexString);
}
protected static bool ContainsTag (string input)
{
const string regexString = @"<[^>]+>";
return Regex.IsMatch(input, regexString);
}
}
}
以上是关于csharp NotAllowedHtml.cs是一个数据注释addi的主要内容,如果未能解决你的问题,请参考以下文章
csharp 委托是回调函数
csharp 检查当前用户是否是管理员。
csharp 检查当前用户是否是管理员。
关于异常Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
csharp 独立类中间件是基于约定的
csharp 使用的示例是和作为关键字。