2014-01-09 82 views
2

嘿大家我想弄清楚如何重新编写一个网址,如www.mywebsit.com/Articles/newsInfo.aspx?id=3到www.mywebisite.com /Articles/My-News-Title.aspxASP.net URL重写基于查询字符串ID

我不知道我是不是误解了一些东西,但是下面是我的代码,而且似乎没有任何事情发生。网址保持不变。

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) 
    Dim currPath As String = Request.Url.ToString 

    If currPath.IndexOf("Articles") <> -1 And currPath.IndexOf("?np=") <> -1 Then 
     currPath = currPath.Substring(currPath.IndexOf("?np=") + 4) 
     Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConString").ConnectionString 
     Dim myreader As System.Data.SqlClient.SqlDataReader 
     Using myConnection As New System.Data.SqlClient.SqlConnection(connectionString) 
      Try 
       myConnection.Open() 
       Dim myCommand As New System.Data.SqlClient.SqlCommand() 


       myCommand.CommandType = Data.CommandType.Text 
       myCommand.CommandText = "SELECT TheNewsTitle FROM TheNews WHERE TheNewsId=" & currPath.Replace("'", "''") 
       myCommand.Connection = myConnection 

       myreader = myCommand.ExecuteReader 
       If myreader.HasRows Then 
        myreader.Read() 
        HttpContext.Current.RewritePath("~/Articles/" & myreader.GetValue(0).ToString.Replace(" ", "-") & ".aspx") 
        myreader.Close() 

       End If 

       myConnection.Close() 
       myCommand.Dispose() 
       myConnection.Dispose() 

      Catch ex As Exception 
       myConnection.Close() 
       myConnection.Dispose() 
      End Try 
     End Using 
    End If 
End Sub 

该代码从未错误,所以我不明白发生了什么事情。

回答

3

你想要做实际的URL重写吗?换句话说 - 你想在你的网站上的链接看起来像

www.mywebsite.com/Articles/My-News-Title.aspx

处理

www.mywebsite.com/Articles/newsInfo.aspx?id=3

是吗?

看看这里: -

http://msdn.microsoft.com/en-us/library/cc668201.aspx

http://msdn.microsoft.com/en-us/library/dd329551.aspx

+0

这些让我在正确的方向。我花了一段时间才把头部缠绕在一些概念上。谢谢一堆! – Tommy

+0

不客气Tommy :) – sh1rts