2016-08-02 53 views
1

嗨,我想以編程方式更改webconfig中的頁面重定向。 我在web配置中有以下代碼。以編程方式更改網頁配置中的頁面重定向

<location path="WebForm2.aspx"> 
    <system.webServer> 
     <httpRedirect enabled="true" destination="http://google.com" httpResponseStatus="Permanent" /> 
    </system.webServer> 
    </location> 

我想使用c#編程啓用或禁用httpredirect。 請告訴我如何做到這一點。

+0

你檢查了這個http:///stackoverflow.com/questions/270287/editing-web-config-programatically – Rahul

回答

0

我試過Rahul建議的代碼,但我無法以編程方式更改Web.config<location>元素。

作爲替代,您可以編寫一個HttpHandler攔截請求WebForm2.aspx頁面,將用戶重定向到另一個網址:

處理程序:

namespace StackOverflowHelp 
{ 
    public class RedirectHandler : IHttpHandler 
    { 
     public bool IsReusable 
     { 
      get { return true; } 
     } 

     public void ProcessRequest(HttpContext context) 
     { 
      Uri uri = context.Request.Url; 

      if (uri.AbsolutePath == "/WebForm2.aspx.aspx") 
       context.Response.Redirect("http://google.com"); 
     } 
    } 
} 

在Web程序登記。配置:

<system.webServer> 
    <handlers> 
     <add verb="*" path="WebForm2.aspx" 
     name="RedirectHandler" 
     type="StackOverflowHelp.RedirectHandler"/> 
    </handlers> 
+0

主席先生,我希望在運行時更改webconfig中的路徑,或更改在運行時啓用或禁用httpRedirect。我不想從後面的代碼重定向頁面,我只想從webconfig中獲得它。我不會在頁面源中放置任何重定向代碼。爲了改變webcofig我使用另一個頁面不是我重定向到的同一頁面。 –