【问题标题】:Rewriting dynamic URL ASP.net重写动态 URL ASP.net
【发布时间】:2015-05-07 22:22:59
【问题描述】:

我知道如何将 url 重写为web.conf,但问题是我必须从 url 中给出的 id 中知道要放入重写的 url 中的名称 foo/5 应该是 foo/bar 因为在数据库中 id 5 的名称为“bar” 我也有告诉我哪个名字被分配了女巫ID的类方法 所以,我想从 web.config 调用类来获取对应 id 的确切名称,然后重写 URL 我看到了使用custom configuration class的可能性,但不知道如何使用。

你能告诉我如何或给我其他建议吗?

【问题讨论】:

  • 上次我做这样的事情,我最终编写了自己的 IHttpModule,它拦截请求,并根据一些条件、查找等重写路径。
  • 你能给我举个例子吗?

标签: asp.net url-rewriting web-config


【解决方案1】:

一般概念是我获取传入的 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 pre version 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>

【讨论】:

  • 感谢您的回复 :) 您还有其他使用 web.config 重写网址的解决方案吗?
  • 我不知道是否可以从web.config动态重写foo/bar到/foo/5。我想这需要您在需要时手动添加新路线。如果您有很多规则,这将是耗时且不可行的选择。
猜你喜欢
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多