【发布时间】:2012-02-04 09:33:37
【问题描述】:
我有一个 asp.net 网络应用程序,现在用户可以通过输入 www.webdomain.com/page.aspx?usename=myusername 来获取配置文件。我想将其更改为 www.webdomain.com/username。感谢您的帮助。
【问题讨论】:
-
我认为您要查找的词是“重定向”。
标签: c# asp.net url-rewriting
我有一个 asp.net 网络应用程序,现在用户可以通过输入 www.webdomain.com/page.aspx?usename=myusername 来获取配置文件。我想将其更改为 www.webdomain.com/username。感谢您的帮助。
【问题讨论】:
标签: c# asp.net url-rewriting
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
);
在我的例子中,我的用户列表在应用程序生命周期内永远不会改变,所以我可以使用静态列表来缓存它。我建议您修改代码,以便您正在做任何检查以确保输入的值是匹配内的用户名。
【讨论】:
使用 MVC 路由。这是一篇关于如何在 webforms 中使用 mvc 路由的好文章:
http://msdn.microsoft.com/en-us/magazine/dd347546.aspx
和
【讨论】:
rewriterule www.webdomain.com/.+? www.webdomain.com/page.aspx?usename=$1
【讨论】:
有几种方法可以做到这一点。您可以使用 ASP.NET MVC 并使用 IRouteConstraint 创建路由以确保用户名存在。
您还可以创建一个 IHttpModule 来捕获 www.webdomain.com/username 的 Application_BeginRequest 和处理请求,并将它们重写或 TransferRequest 到 www.webdomain.com/page.aspx?usename=myusername。
您也可以像在 IHttpModule 中一样直接在 Global.asax 中编写代码。
【讨论】: