我知道如何将url重写为web.conf
,但问题是我必须从url中给出的id知道要放入重写的url例如
foo / 5应该是foo / bar,因为在数据库中id 5的名称为“bar”
我也有类方法告诉我哪个名字是女巫id
所以,我想从web.config中调用该类来获取相应id的确切名称,然后重写URL
我看到了使用custom configuration class
的可能性,但不知道如何使用它。
答案 0 :(得分:0)
一般概念是我接收传入的URL(请求)并将其映射到特定页面。与/blog/my-awesome-post
类似,我们会将其重写为Blog.aspx?id=5
。
public class UrlRewriteModule : IHttpModule
{
public void Dispose()
{
// perform cleanup here if needed.
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest); // attach event handler for BeginRequest event.
}
void context_BeginRequest(object sender, EventArgs e)
{
// get the current context.
HttpContext context = ((HttpApplication)sender).Context;
// the requested url
string requestedUrl = context.Request.Path; // e.g. /blog/my-awesome-post
// if you want to check for addtional parameters from querystring.
NameValueCollection queryString = context.Request.QueryString;
// perform db calls, lookups etc to determine how to rewrite the requested url.
// find out what page to map the url to.
// lets say that you have a page called Blog, and 'my-awesome-post' is the title of blog post with id 5.
string rewriteUrl = "Blog.aspx?id=5";
// rewrite to the path you like.
context.RewritePath(rewriteUrl);
}
}
您需要将模块添加到web.config中的模块列表中:
IIS预版本7。:
<system.web>
<httpModules>
<add name="UrlRewriteModule" type="Assembly.Name.UrlRewriteModule, Your.Namespace.Here" />
....
</httpModules>
.....
</system.web>
IIS 7及更新版本:
<system.webServer>
<modules>
<add name="UrlRewriteModule" type="Assembly.Name.UrlRewriteModule, Your.Namespace.Here" />
....
</modules>
....
</system.webServer>