如何使用 HttpContext 进行重定向

Pos*_*Guy 5 asp.net

我的问题是:

  1. 所以我需要创建一个自定义类/HttpHandler 并将此代码放入其中?或者我可以把它放在其他地方,比如在 global.asax 中吗?
  2. 如何检查传入的主机(例如检查 www.mydomain.com)以便我知道何时重定向?

代码:

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

Pha*_*rus 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");
    }
}
Run Code Online (Sandbox Code Playgroud)