隐藏

ASP.NET之HttpModule拦截404异常

发布:2021/7/13 16:34:31作者:管理员 来源:本站 浏览次数:870

Httpmodule代码: public class Error404Module : IHttpModule
    { public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(Context_Error);
        } protected void Context_Error(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            HttpResponse response = ctx.Response;
            HttpRequest request = ctx.Request;

            Exception ex = ctx.Server.GetLastError();
            HttpException hex = ex as HttpException; if (hex != null && hex.GetHttpCode() == 404)
            {
                ctx.Server.ClearError(); string url = request.Url.AbsoluteUri.ToLower(); if (url.Contains(@"http://hj.woniu.com"))
                {
                    url = url.Replace(@"http://hj.woniu.com", @"http://sg.hj.woniu.com");
                }
                response.Redirect(url, true);
            }
        } public void Dispose()
        {

        }
    } 

Web.Config配置: <httpModules>
      <add name="Error404Module" type="ActHJ.ErrorModules.Error404Module"/>
   </httpModules> 


<system.web>
    <compilation debug="false">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
      </assemblies>
      <buildProviders>
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider" />
        <add extension=".htm" type="System.Web.Compilation.PageBuildProvider" />
      </buildProviders>
    </compilation> 


<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule"/>
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="Error404Module" type="ActHJ.ErrorModules.Error404Module"/>
    </modules>