再次试验用ASP.NET来Redirect

来源:互联网 发布:广东11选5遗漏数据网站 编辑:程序博客网 时间:2024/05/09 12:54
 
再次试验用ASP.NET来Redirect

以前我曾经写过文章介绍如何使用Global.asax来做重定向。可是实践中出现很多问题。

新的项目我使用HttpModule来做。使用HttpModule而不是HttpHandler可以避免无限循环的问题。HttpHandler其实是截获Handler,所有后来的事都要自己手工解决。我只是重新定向,没有这么复杂。HttpModule看上去比较实惠,所以就是这个了。

    public class HttpModule : IHttpModule
    
{
        
public void Dispose()
        
{ }

        
public void Init(HttpApplication context)
        
{
            context.AcquireRequestState 
+= new EventHandler(context_BeginRequest);
        }


        
private void context_BeginRequest(object sender, EventArgs e)
        
{
            
string From = Config.GetAppSettings("From");
            
string To = Config.GetAppSettings("To");
            
string WebAppPath = HttpContext.Current.Request.ApplicationPath;
            From 
= From.Replace("~/""");
            To 
= To.Replace("~/", WebAppPath + "/");

            
if (HttpContext.Current.Request.RawUrl.Contains(From))
            
{
                HttpContext.Current.Server.Transfer(To, 
true);
            }

        }

    }


只要在Web.config里面加上From和To的AppSetting就可以了。Web.config中加入如下httpModule:

<add name="HttpModule" type="HttpModule, MyLib" />

前面是类,后面是dll的文件名。如果IIS中没有这个虚拟文件,要这样设置:打开ISAPI,设置Mapping,勾选Check that file exists, 这样,打开浏览器就可以访问到假地址。