当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Redirecting URL's

问题描述:

How can I redirect www.mysite.com/picture/12345 to www.mysite.com/picture/some-picture-title/12345? Right now, "/picture/12345" is rewritten on picture.aspx?picid=12345 and same for second form of url (picture/picture-title/12323 to picture.aspx?picid12323) I can't just rewrite first form of url to second because i have to fetch picture title from database.

On the first hand, problem looks very easy but having in mind time to parse every request, what would be the right thing to do with it?

网友答案:

Not knowing what is the ASP.NET technology (Webforms or MVC) I will assume it's WebForms.

You can have a look at URL Redirecting and build you own rules. And you do this one time only to apply to all of the links that look like you want.

Scott Guthrie has a very nice post about it.

If what you want is to when it comes to that address redirect to a new one, it's quite easy as well.

First of all let's reuse the code, so you will redirect first to a commum page called, for example, redirectme.aspx

in that page you get the REFERER address using the ServerVariables or passing the Url in a QueryString, it's your chooise and then you can attach the title name, like:

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));
}

to save time on the server do this on the first Page event

protected void Page_PreInit(object sender, EventArgs e)
{
    Redirect();
}
网友答案:

If you're running IIS7 then (for both webforms and MVC) the URL rewriting module (http://learn.iis.net/page.aspx/460/using-url-rewrite-module/) is worth looking at.

Supports pattern matching and regular expressions for redirects, state whether they're temporary or permanent, plus they're all managable through the console. Why code when you don't have to?

网友答案:

I'm presuming you need a common pattern here and not just a once off solution. i.e. you'll need it to work for 12345 & 12346 & whatever other IDs as well. You're probably looking for URLRedirection and applying a Regular Expression to identify a source URI that will redirect to your Target URI

分享给朋友:
您可能感兴趣的文章:
随机阅读: