How to encode custom HTTP headers in C#

前端 未结 5 816
名媛妹妹
名媛妹妹 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 00:59

    You can use the HttpEncoder.HeaderNameValueEncode Method in the .NET Framework 4.0 and above.

    For previous versions of the .NET Framework, you can roll your own encoder, using the logic noted on the HttpEncoder.HeaderNameValueEncode reference page:

    • All characters whose Unicode value is less than ASCII character 32, except ASCII character 9, are URL-encoded into a format of %NN where the N characters represent hexadecimal values.

    • ASCII character 9 (the horizontal tab character) is not URL-encoded.

    • ASCII character 127 is encoded as %7F.

    • All other characters are not encoded.

    Update:

    As OliverBock point out the HttpEncoder.HeaderNameValueEncode Method is protected and internal. I went to open source Mono project and found the mono's implementation

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

    Just FYI

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

提交回复
热议问题