使用httpModules做一些事
阿新 • • 發佈:2017-09-24
rgs ctc 管道 tco module req ring generic query
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程序啟動後會執行可以註冊多個 這是影響全局的配置
使用httpModules做一些事