httpmodules是http管道处理程序 可以重写接口进行一些在请求到达api接口前做全局处理 

这是一个过滤关键词的例子

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Web;

namespace WebApplication4
{
    public class FilterForbiddenWordModule:IHttpModule
    {
        void IHttpModule.Dispose() { }

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

        private static void OnBeginRequest(object sender, EventArgs e)
        {
            var request = (sender as HttpApplication).Request;
            ProcessCollection(request.QueryString);
            ProcessCollection(request.Form);
        }

        private static void ProcessCollection(NameValueCollection collection)
        {
            var copy = new NameValueCollection();
         //   copy.GetType().GetProperty("IsReadOnly").SetValue(copy, false);

            foreach (string key in collection.AllKeys)
            {
                Array.ForEach(
                    collection.GetValues(key),
                    v => copy.Add(key, ForbiddenWord.Filter(v)));
            }
            typeof(NameObjectCollectionBase).GetProperty("IsReadOnly",BindingFlags.Instance | BindingFlags.NonPublic).SetValue(collection, false);
            collection.Clear();
            collection.Add(copy);
        }
    }

    public static class ForbiddenWord
    {
        public static string Filter(string original)
        {
            return original.Replace("关键词", "替换后");
        }
    }
}

配置文件加入该项配置 web程序启动后会执行可以注册多个 这是影响全局的配置

 

posted on 2017-09-24 10:18  xuelei被占用了  阅读(297)  评论(0编辑  收藏  举报