是否有“rawurlencode”的等价物?在C#? [英] Is there any equivalent for "rawurlencode" in C#?

查看:108
本文介绍了是否有“rawurlencode”的等价物?在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有相当于C#中的PHP rawurlencode?我已经尝试了

 HttpUtility.UrlEncode 

 HttpUtility.UrlEncodeUnicode 

但它们并不相同。它显示了像Space'('')'等字符时的问题..

解决方案

两种方法都将空格显示为 + ,所以你可以在使用 UrlEncode %20 替换 + c $ c>:

  string  yourStr =  这里的文字; 
string encodedStr = HttpUtility.UrlEncode(yourStr).Replace( + %20);





如果上述方法没有编码足够的字符,正如您在评论中所说,请使用此功能:

< pre lang =cs> // 首先,将其添加到代码文件的顶部:使用System.Text。 RegularExpressions;
string UrlEncode( string url)
{
Dictionary< string,string> toBeEncoded = new 字典< string,string>(){{ %25},{ %21},{ %23},{ %20},
{


%24},{ & %26},{ ' %27},{ %28},{ %29},{ * %2A},{ + %2B},{ %2C},
{ / %2F},{ %3A},{ ; %3B},{ =,< span class =code-string> %3D},{ < span class =code-string>?, %3F}, { @ %40},{ [ %5B},{ ] %5D}};
Regex replaceRegex = new 正则表达式( @ [%#

&安培;'()* +,/:; = @ \ [\]]);
MatchEvaluator matchEval = match = > toBeEncoded [match.Value];
string encoded = replaceRegex.Replace(url,matchEval);
return 编码;
}



并对网址进行编码:

  string  yourStr =  此处的文字; 
string encodedStr = UrlEncode(yourStr);


Hi, is there an equivalent to the PHP rawurlencode in C#? I've already tried

HttpUtility.UrlEncode

and

HttpUtility.UrlEncodeUnicode

but they're not the same.It shows problem when char like Space '(' ')' etc..

解决方案

Both methods show the space as +, so you can replace + with %20 after using UrlEncode:

string yourStr = "your text here";
string encodedStr = HttpUtility.UrlEncode(yourStr).Replace("+", "%20");



If the above method doesn't encode enough chars, as you said in your comment, use this function:

// first, add this to the top of your code file: using System.Text.RegularExpressions;
string UrlEncode(string url)
{
    Dictionary<string, string> toBeEncoded = new Dictionary<string, string>() { { "%", "%25" }, { "!", "%21" }, { "#", "%23" }, { " ", "%20" },
    { "


", "%24" }, { "&", "%26" }, { "'", "%27" }, { "(", "%28" }, { ")", "%29" }, { "*", "%2A" }, { "+", "%2B" }, { ",", "%2C" }, { "/", "%2F" }, { ":", "%3A" }, { ";", "%3B" }, { "=", "%3D" }, { "?", "%3F" }, { "@", "%40" }, { "[", "%5B" }, { "]", "%5D" } }; Regex replaceRegex = new Regex(@"[%!#


&'()*+,/:;=?@\[\]]"); MatchEvaluator matchEval = match => toBeEncoded[match.Value]; string encoded = replaceRegex.Replace(url, matchEval); return encoded; }


And to encode the URL:

string yourStr = "your text here";
string encodedStr = UrlEncode(yourStr);


这篇关于是否有“rawurlencode”的等价物?在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆