通过拦截回发来清理用户输入 - 全球 - ASP.Net 3.5 C#

时间:2012-06-21 11:56:07

标签: c# asp.net .net-3.5 master-pages postback

我有一个现有项目,所以我需要一种全面清理/检查用户输入的方法。

我有一个拥有form标签的母版页(父母),“儿童”页面包含带有回发命令的表单元素,插入/更新/删除数据库等。

仅使用C# - 在帖子通过子页面运行之前,我是否可以通过某种方式全局拦截回发?

是否有可能检查文本框/复选框/ radioButton等是否以不同的方式操纵用户输入的清理?

3 个答案:

答案 0 :(得分:1)

这就是我为了让它发挥作用而做的。

  • 覆盖我的主页上的OnInit事件

  • 为我的Request集合禁用ReadOnly,使其可设置。

  • 循环发布.Net控件,清理值并设置新值。

  • 重新启用ReadOnly。

在全球范围内运作良好,节省了我几天的体力劳动:)

protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (IsPostBack)
        {
            var fCollection = (NameValueCollection)Request.GetType().GetField("_form", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Request);
            PropertyInfo oReadable = fCollection.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
            oReadable.SetValue(fCollection, false, null);

            foreach (string s in Request.Params.Keys)
            {
                var pCtrl = Page.FindControl(s);

                //Sanitize the posted values (TextHandler.SimpleSanitize is my own static method)
                if (pCtrl != null) fCollection[s] = TextHandler.SimpleSanitize(fCollection[s]);
            }

            oReadable.SetValue(fCollection, true, null);

        }
    }

答案 1 :(得分:0)

您可以使用处理context.BeginRequest事件的自定义IHttpModule执行某些操作。

public class MyHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(OnBeginRequest);
    }

    protected void OnBeginRequest(object sender, EventArgs e)
    {
        var context = ((HttpApplication) sender).Context;
        // do something here, use the context to get request info
    }

    public void Dispose()
    {
    }
}

您必须在web.config中注册HttpModule,例如:

<httpModules>
  <add name="MyHttpModule" type="MyProject.MyNamespace.MyHttpModule, MyProject"/>
</httpModules>

答案 2 :(得分:-1)

只需在您的MasterPage标记中添加Jquery功能,该功能将拦截您需要的所有事件,并根据您的需要进行操作。要捕获只需要控件,您可以应用css类