How to redirect using HttpContext

My questions:

  • So, do I need to create a custom class / HttpHandler and throw this code into it? Or can I place this somewhere else, as in global.asax?
  • How can I check the incoming host (so I need to check on www.mydomain.com) so that I know when to redirect?

the code:

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

Paste this into the new .cs file in the App_Code folder:

 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() { } } 

Then add this to your web.config in system.web:

 <httpModules> <add type="TestModule" name="TestModule" /> </httpModules> 
+1
source

You can place it in Global.asax in the Application_BeginRequest event.

 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"); } } 
0
source

I avoid putting something unnecessary in global.asax as it tends to become cluttered. Create an HttpModule instead, add an event handler

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

and, in the beginRequest method,

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

All Articles