【问题标题】:how to do a url rewrite in asp.net with just a username如何仅使用用户名在 asp.net 中进行 url 重写
【发布时间】:2012-02-04 09:33:37
【问题描述】:

我有一个 asp.net 网络应用程序,现在用户可以通过输入 www.webdomain.com/page.aspx?usename=myusername 来获取配置文件。我想将其更改为 www.webdomain.com/username。感谢您的帮助。

【问题讨论】:

  • 我认为您要查找的词是“重定向”。

标签: c# asp.net url-rewriting


【解决方案1】:

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
        );

在我的例子中,我的用户列表在应用程序生命周期内永远不会改变,所以我可以使用静态列表来缓存它。我建议您修改代码,以便您正在做任何检查以确保输入的值是匹配内的用户名。

【讨论】:

  • 我还没有对此进行测试,因为我无法将其转换为 asp.net new { IsUserAction = new IsUserActionConstraint() }
  • 张贴您用来注册路线的完整代码块,我会给您一些帮助。 new {} 只是一个匿名对象或类型,在 .NET 3.0 中引入了此功能。左边只是一个变量名,右边是创建类的一个实例。根据您放置类文件的位置,您可能需要调整类的命名空间,例如 new Path.To.Class.IsUserActionConstraint()
  • 使用 asp.net 4.0。并且该参数期望 bool checkphysicalUrlAddress: routeCollection.MapPageRoute("RouteForUser", "{username}", "~/Userprofile.aspx", new IsUserActionConstraint() );
  • 如果你从不调用 match 方法,它是如何运行的?
  • 好吧,我知道你不能在 asp.net 中运行它,只能在 mvc 中运行
【解决方案2】:

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

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

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

【讨论】:

  • 很好的例子。我现在可以做 www.example.com/u/username。我将如何摆脱 /u 而只有 /username,它说重新路由不能以 / 开头
  • 您需要为“{Username}”注册一个路由,我建议创建一个 IRouteConstraint 来强制路由仅在输入的值是用户名时匹配。见stackoverflow.com/questions/4988138/…stephenwalther.com/blog/archive/2008/08/07/…
  • 无论如何你可以给我看一个asp.net形式的例子。我有 IRouteConstraint 类,但我不知道如何使用它。谢谢
【解决方案3】:
rewriterule www.webdomain.com/.+? www.webdomain.com/page.aspx?usename=$1

【讨论】:

    【解决方案4】:

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

    您还可以创建一个 IHttpModule 来捕获 www.webdomain.com/username 的 Application_BeginRequest 和处理请求,并将它们重写或 TransferRequest 到 www.webdomain.com/page.aspx?usename=myusername。

    您也可以像在 IHttpModule 中一样直接在 Global.asax 中编写代码。

    【讨论】:

      猜你喜欢
      • 2013-05-30
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 2012-11-18
      • 1970-01-01
      相关资源
      最近更新 更多