2009-11-30 2 views
4

내 질문은 :방법으로 HttpContext로 리디렉션

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

을 HttpModule의를 생성하는 이벤트 핸들러에게

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

를 추가합니다. –

답변

0

당신은 Application_BeginRequest 이벤트에서 Global.asax에 배치 할 수 있어야한다.

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

이 방법으로 _context 필드를 추가하는 것에 미쳐 있지는 않습니다. context_BeginRequest 메소드는 이미 HttpApplication 객체를 보낸 사람 매개 변수로받습니다. –

+0

좋은 지적 이니, 나는 그것을 새롭게 할 것이다. (나는 이것을 메모리에서 빨리 채우고 세부 사항을 기억할 수 없다) –

+0

우리는 App_Code 폴더를 사용하지 않고있다. 우리는 WAP을 사용하고 있습니다. Phaedrus가 확인한 global.asax에 추가하지 않는 것이 좋을까요? 나는 실제로 그것을 직접 테스트했는데 이것에 대한 수업이 필요 없다는 것을 알았습니다 ... 너무 많이합니다. – PositiveGuy

0

을 내가 퍼팅 피하기 그것은 어수선하게되는 경향이 있기 때문에 global.asax에서 불필요한 것. 대신, 당신은 아마이 너무에서 context.Response.StatusCode = (302)을 원의 beginRequest 방법에

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

} 
관련 문제