using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Routing; namespace WebClientService.Modules { public class GateKeeperOfStaticHtml : IHttpModule { // Fields private static readonly object _contextKey = new object(); private static readonly object _requestDataKey = new object(); private RouteCollection _routeCollection; // Properties public RouteCollection RouteCollection { get { if (this._routeCollection == null) { this._routeCollection = RouteTable.Routes; } return this._routeCollection; } set { this._routeCollection = value; } } public void Init(HttpApplication application) { if (application.Context.Items[_contextKey] == null) { application.Context.Items[_contextKey] = _contextKey; application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache); } } private void OnApplicationPostResolveRequestCache(object sender, EventArgs e) { HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context); this.PostResolveRequestCache(context); } /// <summary> /// 检测是否是合法的处理后缀类型 /// </summary> /// <param name="toCheckedStr"></param> /// <returns></returns> private bool IsValidExtension(string toCheckedStr) { bool result = false; if (string.IsNullOrEmpty(toCheckedStr)) { result= false; } if (toCheckedStr.EndsWith(".html", StringComparison.CurrentCultureIgnoreCase)|| toCheckedStr.EndsWith(".htm", StringComparison.CurrentCultureIgnoreCase)) { result= true; } return result; } public virtual void PostResolveRequestCache(HttpContextBase context) { RouteData routeData = this.RouteCollection.GetRouteData(context); if (routeData != null) { //检测路由数据,仅仅监听 html 资源 var controller = routeData.Values.FirstOrDefault(x => x.Key == "controller"); if (default(KeyValuePair<string,object>).Equals(controller)) { //没有控制器数据 不做处理 return; } //检测路由控制器的后缀,是否是 *****.html 或者 *****.htm的格式 if (controller.Value==null) { return; } if (!this.IsValidExtension(controller.Value.ToString())) { return; } IRouteHandler routeHandler = routeData.RouteHandler; if (routeHandler == null) { return; } if (!(routeHandler is StopRoutingHandler)) { RequestContext requestContext = new RequestContext(context, routeData); context.Request.RequestContext = requestContext; IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext); if (httpHandler == null) { return; } try { context.RemapHandler(httpHandler); } catch (Exception ex) { throw ex; } } } } public void Dispose() { throw new NotImplementedException(); } } }
2 注册默认的错误页面
<customErrors defaultRedirect="defaultError.html" mode="On">
<error statusCode="404" redirect="404notfind.html"/>
</customErrors>
</system.web>
3 注册模块
<modules>
<remove name="FormsAuthentication"/>
<add name ="GateKeeper" type="WebClientService.Modules.GateKeeperOfStaticHtml,WebClientService"/>
</modules>