2011-05-06 100 views
5

我得到一个URL字符串,并想将其转换为合法的HTTP网址:如何在ASP MVC编码一个完整的URL字符串

例如:

"http://one/two/three%four/five#five?six seven"应该变成"http://one/two/three%25four/five%23five?six%20seven"

然而,HttpUtility.UrlEncode没有帮助,因为它编码整个字符串(包括合法的"://")。

在此先感谢

回答

4

如果这就是你想要什么看?

Uri uri = new Uri("http://one/two/three%four/#five?six seven"); 
    string url = uri.AbsoluteUri + uri.Fragment; 
    // url will be "http://one/two/three%25four/#five?six%20seven#five?six%20seven" 
+0

是该解决方案适用于任何网址? – 2011-05-06 14:03:33

0

如何分割和重新加入:

string url = "http://one/two/three%four/#five?six seven"; 
string encodedUrl = "http://" + string.Join("/", url.Substring(7).Split('/').Select(part => HttpUtility.UrlEncode(part)).ToArray());