2012-01-06 51 views
0

我有一個asp.net web應用程序,現在用戶可以通過將int放入www.webdomain.com/page.aspx?usename=myusername來獲得配置文件。我想將其更改爲www.webdomain.com/username。謝謝你的幫助。如何使用用戶名在asp.net中進行url重寫

+0

我認爲你正在尋找的詞是「重定向」。 – 2012-01-06 17:03:54

回答

2

樣品IRouteConstraint:

public class IsUserActionConstraint : IRouteConstraint 
{ 
    //This is a static variable that handles the list of users 
    private static List<string> _users; 


    //This constructor loads the list of users on the first call 
    public IsUserActionConstraint() 
    { 
     _users= (from u in Models.Users.Get() select u.Username.ToLower()).ToList(); 
    } 


    //Code for checking to see if the route is a username 
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     return _users.Contains((values["username"] as string).ToLower()); 
    } 


} 

而且,登記在Global.asax路線:

routes.MapRoute(
      "User Profile", // Route name 
      "{username}", 
      new { controller = "User", action = "Index", id = UrlParameter.Optional },// This stuff is here for ASP.NET MVC 
    new { IsUserAction = new IsUserActionConstraint() } //Your IRouteconstraint 
     ); 

就我而言,我的用戶列表從未應用程序生命週期,所以我可以在改變通過使用靜態列表來緩存它。我建議你修改代碼,這樣你就可以做任何檢查以確保輸入的值是Match中的用戶名。

+0

我還沒有測試這個,因爲我有麻煩轉換爲asp.net 新{IsUserAction = new IsUserActionConstraint()} – user516883 2012-01-06 18:30:23

+0

張貼完整的代碼塊,您正在使用註冊您的路線,我會給你有些幫助。 new {}只是一個匿名對象或類型,在.NET 3.0中引入了此功能。左邊只是一個變量名,右邊是創建類的一個實例。根據您放置類文件的位置,您可能需要調整類的命名空間,例如使用asp.net 4.0新Path.To.Class.IsUserActionConstraint() – 2012-01-06 19:18:35

+0

。並且該參數期望爲bool checkphysicalUrlAddress: routeCollection.MapPageRoute(「RouteForUser」,「{username}」,「〜/ Userprofile.aspx」,new IsUserActionConstraint()); – user516883 2012-01-06 20:19:27

1
rewriterule www.webdomain.com/.+? www.webdomain.com/page.aspx?usename=$1 
2

使用MVC路由。這是一個關於如何使用MVC路由與web表單的好文章:

http://msdn.microsoft.com/en-us/magazine/dd347546.aspx

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

+0

很好的例子。我現在可以做www.example.com/u/username。我將如何擺脫/ u,只是有/用戶名,它表示重新路由不能以/ – user516883 2012-01-06 17:30:01

+0

開始您需要爲「{用戶名}」註冊路由,我會建議創建一個IRouteConstraint來強制路由只有當輸入的值是用戶名時才匹配。請參閱http://stackoverflow.com/questions/4988138/how-to-make-irouteconstraint-filter-route或http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip -30-create-custom-route-constraints.aspx – 2012-01-06 17:32:26

+0

有無論如何,你可以向我展示一個asp.net形式的例子。我有IRouteConstraint類,但我不知道如何使用它。謝謝 – user516883 2012-01-06 21:11:19

0

有幾個方法可以做到這一點。您可以使用ASP.NET MVC並使用IRouteConstraint創建一個路徑,以確保用戶名存在。

您也可以創建一個IHttpModule來捕獲www.webdomain.com/username的Application_BeginRequest和handel請求,並將它們重寫或轉發請求到www.webdomain.com/page.aspx?usename=myusername。

您也可以直接在Global.asax中執行代碼,就像您使用IHttpModule一樣。