如何在asp.net中只使用用户名重写url

本文关键字:用户 重写 url asp net | 更新日期: 2023-09-27 18:19:34

我有一个asp.net web应用程序,现在用户可以通过输入int www.webdomain.com/page.aspx来获取配置文件?usename=我的用户名。我想把它改成www.webdomain.com/username。谢谢你的帮助。

如何在asp.net中只使用用户名重写url

示例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中的用户名。

使用MVC路由。这是一篇关于如何在webforms:中使用mvc路由的好文章

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

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

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

有几种方法可以做到这一点。您可以使用ASP.NET MVC并使用IRouteConstraint创建一个路由,以确保用户名存在。

您还可以创建一个IHttpModule,用于捕获Application_BeginRequest和handel对www.webdomain.com/username的请求,并将它们重新写入或TransferRequest到www.webdomaincom/page.aspx?usename=我的用户名。

您也可以直接在Global.asax中执行代码,方法与IHttpModule相同。