每当用户在我的web应用程序中的页面中发布包含<或>的内容时,我都会引发此异常。
我不想因为有人在文本框中输入了字符而引发异常或使整个web应用程序崩溃,但我正在寻找一种优雅的方式来处理这一问题。
捕获异常并显示
出现错误,请返回并重新键入整个表单,但这次请不要使用<
我觉得不够专业。
禁用后验证(validateRequest=“false”)肯定可以避免此错误,但这会使页面容易受到许多攻击。
理想情况下:当发生包含HTML限制字符的回发时,表单集合中的回发值将自动进行HTML编码。因此,我的文本框的.Text属性将是<;html>;
有没有办法让我从处理者那里做到这一点?
正如我对Sel回答的评论所指出的,这是我们对自定义请求验证器的扩展。
public class SkippableRequestValidator : RequestValidator
{
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
if (collectionKey != null && collectionKey.EndsWith("_NoValidation"))
{
validationFailureIndex = 0;
return true;
}
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
对于那些仍然停留在webforms上的人,我发现了以下解决方案,使您只能在一个字段上禁用验证!(我不想在整个页面上禁用它。)
VB.NET:
Public Class UnvalidatedTextBox
Inherits TextBox
Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean
Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)
End Function
End Class
C#:
public class UnvalidatedTextBox : TextBox
{
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);
}
}
现在只需使用<prefix:UnvalidatedTextBox id=“test”runat=“server”/>而不是<asp:TextBox,它应该允许所有字符(这非常适合密码字段!)
对于那些不使用模型绑定、从Request.Form中提取每个参数、确信输入文本不会造成伤害的人,还有另一种方法。这不是一个很好的解决方案,但它可以解决问题。
从客户端,将其编码为uri,然后发送。例如:
encodeURIComponent($("#MsgBody").val());
在服务器端,接受它并将其解码为uri。例如:
string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?
System.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Form["MsgBody"]) :
null;
or
string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?
System.Uri.UnescapeDataString(HttpContext.Current.Request.Form["MsgBody"]) :
null;
请查找UrlDecode和UnescapeDataString之间的差异