2014-10-28 14 views
0

我想實現一個jquery腳本,該腳本在域地址中使用斜槓「/」後的任何名稱,並將用戶重定向到默認頁面帶用戶名的查詢字符串。例如,如果用戶寫入mydomain.com/username,我想將頁面重定向到mydomain.com/default.aspx?name=username。從URL中取出用戶名,並使用該用戶名的查詢字符串進行重定向

我該如何做到這一點? 感謝

SOLUTION

我在global.asa文件中添加以下代碼。

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     Uri uriAddress = new Uri(Request.Url.AbsoluteUri); 

     if (uriAddress.Segments != null && uriAddress.Segments.Length > 1 && !String.IsNullOrEmpty(uriAddress.Segments[1])) 
     { 
      string SegmentUsername = uriAddress.Segments[1]; 
      Response.Redirect("default.aspx?name=" + SegmentUsername);     
     } 
    } 
+1

你應該在服務器端做這件事(解析URL,重定向等)。 JS和jQuery與描述的情況無關。 – Regent 2014-10-28 09:27:11

+1

我認爲從服務器端做到這一點是最好的做法..可能你需要做的URL重寫.. – 2014-10-28 09:28:48

回答

0

這是針對URL重寫一個完整的解決方案.. http://www.codeproject.com/Articles/641758/An-Example-of-URL-Rewriting-With-ASP-NET

文本從那裏.. URL重寫是截取傳入Web請求並重定向請求到不同的資源的過程。執行URL重寫時,通常會檢查請求的URL,並根據其值將該請求重定向到不同的URL。例如,一個網站重組指定目錄或文章的網頁,當通過URL從文章或目錄訪問網頁時,URL會自動移動到Blog目錄。這發生在URL重寫。

+0

有沒有任何關於我的案件的直截了當的文件?從來沒有使用URL修剪,解析....等 – Gloria 2014-10-28 09:40:16

0

這裏是一個典型的例子,這將在您的特定情況下工作.. ,讓你知道如何URL重寫作品..

在asp.net網站上添加這個類App_Code文件夾

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Text.RegularExpressions; 

/// <summary> 
/// Summary description for Class1 
/// </summary> 
public class URLRule 
    { 
     public string URLPateren { set; get; } 
     public string Rewrite { set; get; } 
    } 
    public class ListURL : List<URLRule> 
    { 

     public ListURL() 
     { 
      //may be you need to redefine this rule in order to make it mature. 
      URLRule obj = new URLRule(); 
      obj.URLPateren = "/(.*)?/(.*)"; 
      obj.Rewrite = "default.aspx?name=$2"; 
      Add(obj); 
      //here you can add more rules as above.. 

     } 

     public string Process(string str) 
     { 

      Regex oReg; 

      foreach (URLRule obj in this) 
      { 
       oReg = new Regex(obj.URLPateren); 
       Match oMatch = oReg.Match(str); 

       if (oMatch.Success) 
       { 
        string s = oReg.Replace(str, obj.Rewrite); 
        return s; 
       } 
      } 
      return str; 
     } 
    } 

現在添加此下面這段代碼在你的Global.asax 如果您還沒有然後添加新項目添加它,然後選擇「全局應用程序類」

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 



     ListURL rewriter = new ListURL(); 

     string re = rewriter.Process(Request.Path); 
     if (Request.Path != re) 
     { 
      HttpContext.Current.RewritePath(re); 
     } 



    } 

並且您可以在default.aspx頁面的加載事件中檢查您的查詢字符串值。

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (Request.QueryString.HasKeys()) { 
      string queryvalue = Request.QueryString["name"]; 
      Response.Write("User Name : " + queryvalue); 

     } 
    } 

我想這個網址和工作很好..

本地主機:3030/WebSite3中/ XYZ123

,如果它不能正常工作或然後有URL格局未變嘗試重新定義URLRule。 這裏「xyz123」是名字。 我希望它能正常工作...

相關問題