今天真的被 HttpClient 的 Headers.Authorization 给恶心到了,真的恶心了。
得吐个槽。
using (HttpClient cli = HttpClientFactory.Create()) { cli.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue($"API-PROXY-AUTH;version=1.0,timestamp={stmp},appid={appid},sign={sign}"); cli.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(" ",$"API-PROXY-AUTH;version=1.0,timestamp={stmp},appid={appid},sign={sign}"); cli.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("",$"API-PROXY-AUTH;version=1.0,timestamp={stmp},appid={appid},sign={sign}"); cli.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(null,$"API-PROXY-AUTH;version=1.0,timestamp={stmp},appid={appid},sign={sign}"); var hd = cli.PostAsync($"http://{addr}/api-proxy/v1/callback/call", new StringContent("mydata")).Result; }
如上,各种尝试都是不行。
后来看 AuthenticationHeaderValue 的代码,才发现 AuthenticationHeaderValue 的构造函数必须传入非空的参数(空格都不行)·scheme·,而且还要检查字符,一堆字符不能被包含
[__DynamicallyInvokable] public AuthenticationHeaderValue(string scheme) : this(scheme, null) { } [__DynamicallyInvokable] public AuthenticationHeaderValue(string scheme, string parameter) { HeaderUtilities.CheckValidToken(scheme, "scheme"); this.scheme = scheme; this.parameter = parameter; }
namespace System.Net.Http.Headers { internal static class HeaderUtilities { internal static void CheckValidToken(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } if (HttpRuleParser.GetTokenLength(value, 0) != value.Length) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } }
namespace System.Net.Http { internal static class HttpRuleParser { static HttpRuleParser() { tokenChars = new bool[128]; for (int i = 33; i < 127; i++) { tokenChars[i] = true; } //一堆字符检测,都属于非法字符,比如空格、逗号、等于号、分号、括号等等 tokenChars[40] = false; tokenChars[41] = false; tokenChars[60] = false; tokenChars[62] = false; tokenChars[64] = false; tokenChars[44] = false; tokenChars[59] = false; tokenChars[58] = false; tokenChars[92] = false; tokenChars[34] = false; tokenChars[47] = false; tokenChars[91] = false; tokenChars[93] = false; tokenChars[63] = false; tokenChars[61] = false; tokenChars[123] = false; tokenChars[125] = false; } internal static bool IsTokenChar(char character) { if (character > '\u007f') { return false; } return tokenChars[character]; } internal static int GetTokenLength(string input, int startIndex) { if (startIndex >= input.Length) { return 0; } for (int i = startIndex; i < input.Length; i++) { if (!IsTokenChar(input[i])) { return i - startIndex; } } return input.Length - startIndex; }
参考了 msdn-doc 也没看到说有限制的,却在使用的时候给限制了。。。。。。。
后来,换用了 HttpWebRequest , 想写啥就写啥。
确实有些不理解。