开发者

Taking params from a url

Take these two URLs:

  1. www.mySite.com?name=ssride360

  2. www.mySite.com/ssride360

I know that to get the name param from url 1 you would do:

string name = Request.Params['name'];

But how would I get that for the second url?

I was thinking about attempting to copy the url and remove the known information (www.mySite.com) and then from there I could set name to the remainder.

How would I do a url copy like that? Is there a better way to get 'ssride360' from the second url?

Edit Looking on SO I found some info on copying URLs

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path开发者_如何学编程 = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

Is this the best way for me? each url have one additional param (mySite.com/ssride360?site=SO) for example. Also I know that mySite.com/ssride360 would reference a folder in my project so wouldn't i be getting that file along with it (mySite.com/ssride360/Default6.aspx)?

At this point I think there are better ways then a url copy.

Suggestions?


 Uri x = new Uri("http://www.mySite.com/ssride360");
 Console.WriteLine (x.AbsolutePath);

prints /ssride360


This method will allow you to get the name even if there is something after it. It is also a good model to use if you plan on putting other stuff after the name and want to get those values.

        char [] delim = new char[] {'/'};
        string url = "www.mySite.com/ssride360";
        string name = url.Split(delim)[1];

Then if you had a URL that included an ID after the name you could do:

        char [] delim = new char[] {'/'};
        string url = "www.mySite.com/ssride360/abc1234";
        string name = url.Split(delim)[1];
        string id = url.Split(delim)[2];


URL rewriting is a common solution for this problem. You give it the patterns of the URL's you want to match and what it needs to change it into. So it would detect www.mySite.com/ssride360 and transform it into www.mySite.com?name=ssride360. The user of the website sees the original URL and doesn't know anything changed, but your code sees the transformed URL so you can access the variables in the normal way. Another big plus is that the rules allow you to set the patterns that get transformed as well as the ones that just get passed through to actual folders / files.

http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/


Like javascript? If so...

<script type="text/javascript">
function getName() {
    var urlParts = window.location.pathname.split('/');  //split the URL.
    return urlParts[1];    //get the value to the right of the '/'.
}
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜