Asp.net 如何使用HttpContext重定向
我的问题是:Asp.net 如何使用HttpContext重定向,asp.net,Asp.net,我的问题是: 所以我需要创建一个自定义类/HttpHandler并在其中抛出此代码?或者我可以把它放在其他地方,比如global.asax 如何检查传入的主机(因此请检查www.mydomain.com),以便知道何时重定向 代码: 您应该能够将其放置在全局.asax的应用程序\u BeginRequest事件中 protected void Application_BeginRequest(Object sender, EventArgs e) { HttpContext contex
您应该能够将其放置在
全局.asax
的应用程序\u 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");
}
}
将其粘贴到应用程序代码文件夹中的新.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>
我避免在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
}
我并不热衷于以这种方式添加_context字段。您的context_BeginRequest方法已经接收到一个HttpApplication对象作为其发送方参数。这是一个很好的观点,我将更新它。(我只是快速从记忆中提取出来,记不起细节)我们没有使用App_代码文件夹。我们正在使用WAP(感谢上帝;)。为什么不直接添加到global.asax中呢?Phaedrus已经证实了这一点?事实上,我只是自己测试了一下,我认为没有必要为这个设置一个类……这太多了。只要你只有一个需求,就可以确定。如果您有多个模块类型需求,那么Global.asax文件会变得非常混乱。这也为您提供了项目间可重用的功能。如果您只是使用WAP,则可以在项目中的任何位置创建此类。您可能也希望在其中创建context.Response.StatusCode=302。
public void Rewrite_BeginRequest(object sender, System.EventArgs args)
{
HttpApplication app = (HttpApplication)sender;
/// all request properties now available through app.Context.Request object
}