vs对某些网络错误的拦截

在编写代码的过程中发现如果在写好网页中的文本框内写入js代码(以<script>1</script>输入为例)

vs会自动拦截并报错,如图(密码中我也输入了<script>1</script>)

简单解决方法有两种

1.在网页开头代码中加上ValidateRequest="false"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login"  ValidateRequest="false"%>

这样可以关闭该提示,但不能解决危险性问题,可以通过其他(如写防范代码,替换危险字符)方法来防止造成威胁

2.在Page_Load() 函数下添加新的一个函数

protected void Page_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        if (ex is HttpRequestValidationException)
        {
            Response.Write("<script>请您输入合法字符串。</script>");
            Server.ClearError(); // 如果不ClearError()这个异常会继续传到Application_Error()。
        }
        else
        {
            Response.Write("<script>请勿乱来</script>");
            Server.ClearError();
        }
    }

  这是一种从网上查到的方法,可以在出现该类字符并捕捉到时用其他操作代替报错

原文地址:https://www.cnblogs.com/Phoenix-blog/p/7791660.html