Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

.net - How to encode custom HTTP headers in C#

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...