Dir*_*mar 104
另一种方法是使用 Uri.EscapeUriString(stringToEscape).
Lir*_*una 57
我相信你正在寻找HttpServerUtility.UrlEncode.
System.Web.HttpUtility.UrlEncode(string url)
Run Code Online (Sandbox Code Playgroud)
小智 46
我觉得很有用 System.Web.HttpUtility.UrlPathEncode(string str);
它用%20替换空格而不用+替换.
Dar*_*elk 14
正如批准的故事所评论的那样,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"
Run Code Online (Sandbox Code Playgroud)