2010-05-04 124 views

回答

-1

Mayeb這一個? UrlEncode Function

+0

我正在尋找一種方法,不執行URL所需的編碼,但只考慮HTTP標頭的特定限制 – antonio 2010-05-05 01:05:33

-1

對不起,它關閉我的頭頂,但對於您的請求對象應該有一個標題對象,你可以添加到。

即request.headers.add(「blah」);

這不是現貨,但它應該指向正確的方向。

+0

問題是關於編碼標頭值,而不是添加標頭。 – 2012-06-08 20:28:54

7

您可以在.NET Framework 4.0及更高版本中使用HttpEncoder.HeaderNameValueEncode Method

  • 所有字符,其Unicode值小於ASCII字符32:

    對於.NET Framework的早期版本中,你可以推出自己的編碼器,使用邏輯HttpEncoder.HeaderNameValueEncode參考頁面上指出, (ASCII字符9除外)均以URL編碼爲%NN格式,其中N個字符表示十六進制值。

  • ASCII字符9(水平製表符)不是URL編碼的。

  • ASCII字符127被編碼爲%7F。

  • 所有其他字符不編碼。

更新:

由於OliverBock指出HttpEncoder.HeaderNameValueEncode方法是受保護和內部。我去開源Mono項目,發現單的實現

void HeaderNameValueEncode (string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue) 
{ 
     if (String.IsNullOrEmpty (headerName)) 
       encodedHeaderName = headerName; 
     else 
       encodedHeaderName = EncodeHeaderString (headerName); 

     if (String.IsNullOrEmpty (headerValue)) 
       encodedHeaderValue = headerValue; 
     else 
       encodedHeaderValue = EncodeHeaderString (headerValue); 
} 

static void StringBuilderAppend (string s, ref StringBuilder sb) 
{ 
     if (sb == null) 
       sb = new StringBuilder (s); 
     else 
       sb.Append (s); 
} 

static string EncodeHeaderString (string input) 
{ 
     StringBuilder sb = null; 

     for (int i = 0; i < input.Length; i++) { 
       char ch = input [i]; 

       if ((ch < 32 && ch != 9) || ch == 127) 
         StringBuilderAppend (String.Format ("%{0:x2}", (int)ch), ref sb); 
     } 

     if (sb != null) 
       return sb.ToString(); 

     return input; 
} 

僅供參考

[這裏](https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web.Util/HttpEncoder.cs

+1

HeaderNameValueEncode()是受保護的+內部的。 – 2013-12-12 05:36:37

+1

@OliverBock你是對的,更新了帖子。 – liuhongbo 2013-12-12 18:36:29

+0

不幸的是,這個版本和.NET版本(通過Reflector看到)都不能正確編碼數據中已有的'%'字符。 – 2013-12-12 21:19:26

0

這做同樣的工作作爲HeaderNameValueEncode(),也將編碼%字符,以便後面可以可靠地解碼標題。

static string EncodeHeaderValue(string value) 
{ 
    return Regex.Replace(value, @"[\u0000-\u0008\u000a-\u001f%\u007f]", (m) => "%"+((int)m.Value[0]).ToString("x2")); 
} 

static string DecodeHeaderValue(string encoded) 
{ 
    return Regex.Replace(encoded, @"%([0-9a-f]{2})", (m) => new String((char)Convert.ToInt32(m.Groups[1].Value, 16), 1), RegexOptions.IgnoreCase); 
} 
2

對我幫助Uri.EscapeDataString(headervalue)