How to encode custom HTTP headers in C#

前端 未结 5 822
名媛妹妹
名媛妹妹 2020-12-19 00:45

Is there a class similar to HttpUtility to encode the content of a custom header? Ideally I would like to keep the content readable.

5条回答
  •  既然无缘
    2020-12-19 01:06

    This does the same job as HeaderNameValueEncode(), but will also encode % characters so the header can be reliably decoded later.

    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);
    }
    

提交回复
热议问题