重定向URL

时间:2009-05-06 08:38:00

标签: c# asp.net redirect

如何将www.mysite.com/picture/12345重定向到www.mysite.com/picture/some-picture-title/12345?现在,“/ picture / 12345”被重写在picture.aspx?picid = 12345和第二种形式的url(图片/图片标题/ 12323到picture.aspx?picid12323)相同我不能只重写第一种形式url到秒,因为我必须从数据库中获取图片标题。

第一方面,问题看起来很容易,但是考虑到解析每个请求的时间,用它做什么是正确的?

3 个答案:

答案 0 :(得分:3)

不知道什么是ASP.NET技术(Webforms或MVC)我会假设它是WebForms。

您可以查看URL重定向并构建自己的规则。而这样做一次只适用于所有你想要的链接。

Scott Guthrie有一个very nice post

如果您希望将该地址重定向到新地址,那么它也很容易。

首先让我们重用代码,这样您就会首先重定向到名为的通讯页面,例如 redirectme.aspx

在该页面中,您使用ServerVariables获取 REFERER 地址或在QueryString中传递Url,这是您的选择,然后您可以附加标题名称,如:

private void Redirect()
{
    // get url: www.mysite.com/picture/12345
    string refererUrl = Request.ServerVariables["HTTP_REFERER"];    // using the ServerVariables or Request.UrlReferrer.AbsolutePath;
    //string refererUrl = Request.QueryString["url"];                 // if you are redirecting as Response.Redirect("redirectme.aspx?" + Request.Url.Query);

    // split the URL by '/'
    string[] url = refererUrl.Split('/');

    // get the postID
    string topicID = url[url.Length-1]; 

    // get the title from the post
    string postTitle = GetPostTitle(topicID);

    // redirect to: www.mysite.com/picture/some-picture-title/12345
    Response.Redirect(
        String.Format("{0}/{1}/{2}",
            refererUrl.Substring(0, refererUrl.Length - topicID.Length),
            postTitle,
            topicID));
}

节省服务器上的时间在第一个Page事件

上执行此操作
protected void Page_PreInit(object sender, EventArgs e)
{
    Redirect();
}

答案 1 :(得分:1)

如果你正在运行IIS7(对于webforms和MVC),URL重写模块(http://learn.iis.net/page.aspx/460/using-url-rewrite-module/)值得一看。

支持重定向的模式匹配和正则表达式,说明它们是临时的还是永久的,加上它们都可以通过控制台进行管理。为什么不用时编码?

答案 2 :(得分:0)

我认为你需要一个共同的模式而不仅仅是一次性的解决方案。即你需要它来工作12345& 12346&无论其他ID如何。您可能正在寻找URLRedirection并应用正则表达式来标识将重定向到目标URI的源URI

相关问题