【发布时间】:2015-01-15 15:12:47
【问题描述】:
我想动态地从数据库中进行 url 映射。 例如: 我有,
我想,
【问题讨论】:
-
您是否考虑过迁移到 ASP.NET MVC 框架?
-
没有。我正在使用 asp.net 3.5 框架
标签: c# asp.net url-rewriting web-config url-mapping
我想动态地从数据库中进行 url 映射。 例如: 我有,
我想,
【问题讨论】:
标签: c# asp.net url-rewriting web-config url-mapping
这个解决方案非常激烈,但仍然是一个有效的解决方案。
几年前我们在工作中遇到了同样的问题(在我们迁移到 ASP.NET MVC 之前,我强烈建议这样做)。
首先,我们制作了一个新的 ASP.NET 模块(并在 IIS 或 Web.config 上注册了它)。该模块将接收传入客户端的请求。
我们构建了自己的HttpModule,并使其在配置文件中工作,我们在其中定义了有效路由,在您的情况下为http://www.example.com/Men/。
然后我们会有一个经理列表。这些经理将作为管道工作。每个经理都会收到前一个经理的输出。
按照这种方法,我们的第一个管理器是 RewriteManager,它处理传入请求 URL 的重写,因此未来的管理器(和旧的管理器)可以继续使用我们的 aspx URL。
这是我们模块配置文件中的一个路由示例:
<configuration name="note"
mode="1"
urlPattern="^https?://(([a-z0-9\-]*\.)?localhost(:[0-9]+)?/((?'note_id'[0-9]+)-?(?'title'.*))$"
rewriteUrl="/note.aspx?note_id={note_id}&site={ContextInfo.site}">
<manager type="LaNacion.Framework.Web.Managers.RewriteManager, LaNacion.Framework.Web.Managers"/>
<!-- THESE MANAGERS NEED THE ASPX URL, THEY ARE LEGACY MANAGERS -->
<manager type="LaNacion.Framework.Web.Managers.FileCacheManager, LaNacion.Framework.Web.Managers"/>
<manager type="LaNacion.Hola.Web.Managers.NotaManager, LaNacion.Hola.Web.Managers"/>
<manager type="LaNacion.Framework.Web.Managers.OutputImageCacheManager, LaNacion.Framework.Web.Managers"/>
</configuration>
如您所见,我们在正则表达式中定义路由,并使用正则表达式上的命名组来收集所需信息。我们稍后使用我们回忆的信息构建了我们的旧 URL。
在你的情况下,urlPattern 属性看起来像:
https?://(([a-z0-9\-]*\.)?localhost(:[0-9]+)?/(?'entity'[a-zA-Z]+)
rewriteUrl 属性将是:
/Category.aspx?cid=c001&cname={entity}
我们使用HttpContext 实例的RewritePath 方法重写URL:
System.Web.HttpContext.Current.RewritePath(newUrl);
然后,未来的管理器将能够像往常一样提取查询参数,使传统管理器的工作方式与以前相同。
我希望我说得足够清楚,这对你有帮助。
【讨论】:
如果您已经知道您的重写规则,上述@Mati-Cicero 描述的解决方案效果很好。如果你想走这条路,我也建议http://weblogs.asp.net/scottgu/tip-trick-url-rewriting-with-asp-net 上的文章(一篇旧但很好的文章)。
但是如果你想重写存储在数据库中的 URL,这是我的建议:
以这种方式创建一个 HttpModule:
public class DBRewriteModule : IHttpModule
{
public DBRewriteModule()
{
}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
Rewriter rw = new Rewriter();
rw.Process();
}
}
将其添加到您的 web.config 文件中,如下所示:
<system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <add name="DBRewrite" type="smartdev.web.Modules.DBRewriteModule" /> </modules> </system.webServer>
在你的重写器cs文件中你应该有类似的东西:
public class Rewriter
{
public Rewriter()
{
}
public bool Process()
{
// get path from database based on your original path:
// use HttpContext.Current.Request.Path and HttpContext.Current.Request.QueryString
string substPath = "...your db logic here ...";
HttpContext.Current.RewritePath(substPath);
}
}
【讨论】: