如何使用HttpContext重定向

时间:2009-11-30 19:59:46

标签: asp.net

我的问题是:

  1. 所以我需要创建一个自定义类/ HttpHandler并在其中抛出此代码?或者我可以将其放在其他地方,例如global.asax?
  2. 如何检查主机(请检查www.mydomain.com)收件人,以便知道何时重定向?
  3. 代码:

    if ("comes from certain domain")
    {
      context.Response.Status = "301 Moved Permanently";
      context.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
    }
    

3 个答案:

答案 0 :(得分:1)

将其粘贴到App_Code文件夹中的新.cs文件中:

using System;
using System.Web;

public class TestModule : IHttpModule
{
    public void Init(HttpApplication context) {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e) {
        HttpApplication app = (HttpApplication)sender;
        if (app.Request.Url.Host == "example.com") {
            app.Response.Status = "301 Moved Permanently";
            app.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
        }
    }

    public void Dispose() {
    }
}

然后将其添加到system.web中的web.config:

<httpModules>
     <add type="TestModule" name="TestModule" />
</httpModules>

答案 1 :(得分:0)

您应该可以将其放在Global.asax事件的Application_BeginRequest中。

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpContext context = HttpContext.Current;
    string host = context.Request.Url.Host;
    if (host == "www.mydomain.com")
    {
        context.Response.Status = "301 Moved Permanently";
        context.Response.AddHeader("Location", 
                              "http://www.testdomain.com/Some.aspx");
    }
}

答案 2 :(得分:0)

我避免在global.asax中添加任何不必要的内容,因为它往往会变得混乱。相反,创建一个HttpModule,添加一个事件处理程序

public void Init(System.Web.HttpApplication app)
{
    app.BeginRequest += new System.EventHandler(Rewrite_BeginRequest);
}

,在beginRequest方法中,

public void Rewrite_BeginRequest(object sender, System.EventArgs args)
{
   HttpApplication app = (HttpApplication)sender;
   /// all request properties now available through app.Context.Request object

}