利用HttpModule实现浏览器版本控制

实现后的效果:对于非IE浏览器和IE5以下浏览器转向指定说明页面。
如果需要可以自己扩展让浏览器转向不同的浏览器页面。原来在javascrpt里面控制,代码加起来麻烦,利用HttpModule实现更简单。

cs——————————————————————————————————————————————————————————————
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;

namespace Xingmai.WebSite.BrowserChooser
{
    public class BrowserModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        {
           
        }

        public void Init(HttpApplication application)
        {
            //添加判断事件
            application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)source;
            HttpBrowserCapabilities browser = Application.Context.Request.Browser;
            //浏览器版本控制
            //现有控制为IE 5 以上
            if (browser.Browser != "IE" || browser.MajorVersion < 5)
            {
                string strBrowserChooserPage = "";
                try
                {
                    strBrowserChooserPage = ConfigurationManager.AppSettings["BrowserChooserPage"];
                }
                catch (System.Configuration.ConfigurationErrorsException ex)
                {
                    throw new Exception(string.Format("请正确配置web.config AppSetting[BrowserChooserPage]节点,系统错误提示:{0}", ex.Message));
                }
                catch(System.Exception ex)
                {
                    throw ex;
                }
               
                //判断是否请求版本控制错误页面,不是转向,是则不转向
                if (!Application.Context.Request.Url.ToString().Contains(strBrowserChooserPage.Replace("~/","")))
                {
                    Application.Context.Response.Redirect(strBrowserChooserPage);
                }
            }
        }

        #endregion
    }
}

web.config <appSettings> 配置节点————————————————————————————————————————
<add key="BrowserChooserPage" value="~/BrowserChooserNoticePage.htm"/>

web.config <system.web> <httpModules> 配置节点—————————————————————————————————
<add name="BrowserModule" type="Xingmai.WebSite.BrowserChooser.BrowserModule, Xingmai.WebSite.BrowserChooser"/>


参考:
HTTP运行期与页面执行模型 http://www.cnblogs.com/stwyhm/archive/2006/08/08/470972.html
一点一点学ASP.NET之基础概念——HttpModule http://www.cnblogs.com/stwyhm/archive/2006/08/09/471729.html
一点一点学ASP.NET之示例——HttpModule 示例 http://www.cnblogs.com/stwyhm/archive/2006/08/11/473974.html

你可能感兴趣的:(Module)