簡體   English   中英

如何僅用用戶名在asp.net中進行URL重寫

[英]how to do a url rewrite in asp.net with just a username

我有一個asp.net Web應用程序,現在用戶可以通過將int www.webdomain.com/page.aspx?usename=myusername放入該配置文件中。 我想將其更改為www.webdomain.com/username。 謝謝你的幫助。

使用MVC路由。 這是一篇關於如何在Webforms中使用MVC路由的好文章:

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

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

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中的用戶名。

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

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

您還可以創建一個IHttpModule來捕獲Application_BeginRequest和對www.webdomain.com/username的處理請求,並將它們重新寫入或TransferRequest到www.webdomain.com/page.aspx?usename=myusername。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM