每当用户在我的web应用程序中的页面中发布包含<或>的内容时,我都会引发此异常。
我不想因为有人在文本框中输入了字符而引发异常或使整个web应用程序崩溃,但我正在寻找一种优雅的方式来处理这一问题。
捕获异常并显示
出现错误,请返回并重新键入整个表单,但这次请不要使用<
我觉得不够专业。
禁用后验证(validateRequest=“false”)肯定可以避免此错误,但这会使页面容易受到许多攻击。
理想情况下:当发生包含HTML限制字符的回发时,表单集合中的回发值将自动进行HTML编码。因此,我的文本框的.Text属性将是<;html>;
有没有办法让我从处理者那里做到这一点?
最后但同样重要的是,请注意ASP.NET数据绑定控件在数据绑定期间自动编码值。这将更改ItemTemplate中包含的所有ASP.NET控件(TextBox、Label等)的默认行为。以下示例演示了(ValidateRequest设置为false):
aspx
<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication17._Default" %> <html> <body>
<form runat="server">
<asp:FormView ID="FormView1" runat="server" ItemType="WebApplication17.S" SelectMethod="FormView1_GetItem">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="<%#: Item.Text %>"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Text="<%#: Item.Text %>"></asp:TextBox>
</ItemTemplate>
</asp:FormView>
</form>
代码隐藏
public partial class _Default : Page
{
S s = new S();
protected void Button1_Click(object sender, EventArgs e)
{
s.Text = ((TextBox)FormView1.FindControl("TextBox1")).Text;
FormView1.DataBind();
}
public S FormView1_GetItem(int? id)
{
return s;
}
}
public class S
{
public string Text { get; set; }
}
案例提交值:';
标签1.文本值:';
TextBox2.文本值:&#39;
案例提交值:<script>alert('attack!')</脚本>
标签1.文本值:<script>alert('attack!')</脚本>
TextBox2.文本值:<;脚本>;警报(';攻击!';)</脚本>;
如果您使用的是framework 4.0,则web.config中的条目(<pages validateRequest=“false”/>)
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
如果您使用的是框架4.5,则web.config中的条目(requestValidationMode=“2.0”)
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>
如果你只想要一个页面,那么在aspx文件中,你应该把第一行放在下面:
<%@ Page EnableEventValidation="false" %>
如果您已经有类似于<%@页面的内容,那么只需添加rest=>EnableEventValidation=“false”%>
我建议不要这样做。
前面的答案很好,但没有人说过如何排除一个字段进行HTML/JavaScript注入的验证。我不知道以前的版本,但在MVC3 Beta版中,您可以这样做:
[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]
public virtual ActionResult Edit(int id, FormCollection collection)
{
...
}
这仍然会验证除排除的字段之外的所有字段。这一点的好处是,您的验证属性仍然验证字段,但您没有得到“潜在危险的请求。表单值已从客户端检测到”异常。
我已经用它验证了正则表达式。我制作了自己的ValidationAttribute,以查看正则表达式是否有效。由于正则表达式可以包含类似于脚本的内容,我应用了上面的代码-正则表达式仍然在检查是否有效,但不检查是否包含脚本或HTML。