我想打一个字符串转换为使用C#的URL。 一定有什么东西在.NET框架应该帮助,对不对?
Answer 1:
我相信你正在寻找HttpServerUtility.UrlEncode 。
System.Web.HttpUtility.UrlEncode(string url)
Answer 2:
这样做的另一种方法是使用Uri.EscapeUriString(stringToEscape)
Answer 3:
我发现有用System.Web.HttpUtility.UrlPathEncode(string str);
它取代有20%,而不是与+空格。
Answer 4:
要正确逃生空间以及特殊字符的其余部分,使用System.Uri.EscapeDataString(string stringToEscape)
Answer 5:
由于在批准的故事,发表了意见HttpServerUtility.UrlEncode方法替代空间与代替%20 +。 使用这两种方法,而不是一个: Uri.EscapeUriString()或Uri.EscapeDataString()
示例代码:
HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//"https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"
Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//"https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//"https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"
//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//"https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//"https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"
Answer 6:
使用HttpServerUtility.UrlEncode
Answer 7:
我需要做这个也发现了这个问题,从年前,但问题的标题和文字不太匹配,并采用Uri.EscapeDataString
或UrlEncode
(不要使用一个请!)通常不会意义,除非我们在谈论传递的网址作为参数传递给其他网址。
(例如,在做开放ID认证,天青AD,等时传递一个回调URL)
希望这是更务实的问题的答案: 我想打一个字符串转换为使用C#中的网址,一定是有什么在.NET框架应该帮助,对不对?
是的 -两个功能是在C#使URL字符串有帮助
-
String.Format
格式化的URL -
Uri.EscapeDataString
在URL转义任何参数
此代码
String.Format("https://site/app/?q={0}&redirectUrl={1}",
Uri.EscapeDataString("search for cats"),
Uri.EscapeDataString("https://mysite/myapp/?state=from idp"))
产生这一结果
https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp
可以安全地复制并粘贴到浏览器的地址栏,或者src
一个HTML的属性A
标签,或者使用curl
,或者编码成QR码等。
Answer 8:
HttpUtility.UrlEncode方法(String)
Answer 9:
在下面的代码将取代具有单个%20字符重复空间。
例:
输入是:
Code by Hitesh Jain
输出:
Code%20by%20Hitesh%20Jain
码
static void Main(string[] args)
{
Console.WriteLine("Enter a string");
string str = Console.ReadLine();
string replacedStr = null;
// This loop will repalce all repeat black space in single space
for (int i = 0; i < str.Length - 1; i++)
{
if (!(Convert.ToString(str[i]) == " " &&
Convert.ToString(str[i + 1]) == " "))
{
replacedStr = replacedStr + str[i];
}
}
replacedStr = replacedStr + str[str.Length-1]; // Append last character
replacedStr = replacedStr.Replace(" ", "%20");
Console.WriteLine(replacedStr);
Console.ReadLine();
}
Answer 10:
HttpServerUtility.HtmlEncode
从文档:
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
但是,这实际上编码的HTML,而不是URL。 而是使用以UrlEncode(的TestString)。