問題描述:近在項目中有一個需求爲須要在 Http
的Header裏面添加一個User-Agent參數,當請求時。項目自己的目標框架是 .NET Standard 2.0
。因而,在項目源碼中發現了,最終調用的請求是使用 HttpWebRequest
來進行最後的封裝和發送的。web
首先是用 HttpRequest
包裝的,代碼以下:c#
request.Headers["User-Agent"] = "Windows 10.0.2.4";
而後到最後發請求時,foreach
這個Headers 的 Dictionary<string,string> 類型的,而後copy to HttpWebRequest
的這個Header中api
foreach (var header in request.Headers) { httpWebRequest.Headers.Add(header.Key, header.Value); }
本地也進行了相關的 UT 和 FT,一切都很完美。而後發佈了新版本。app
版本發佈後的第三天,接到了用戶的一個反饋說:框架
在調用最新Nuget版本的包後,請求調用一直報錯:必須使用適當的屬性和方法修改 User-Agent測試
首先先讓用戶回退到上一個版本的包,而後詢問了用戶的目標框架,用戶說是.Net framework 4.6.1
,剛開始我覺得是否是我項目中引用的某個包不支持該版本啊,沿着這個思路,果真有所發現。我發如今獲取用戶當前系統版本的時候使用了這個類System.Runtime.InteropServices.RuntimeInformation.OSDescription,而後我發現這個屬性可能爲空,是否是屬性空致使這個錯誤的呢?抱着試一試的態度,繼續往下。.net
去官方文檔看了看,這個包最低支持的.net framework 框架爲 4.7.1 。我想,那若是我在目標框架中也包含了.net framework 4.7.1 會不會就不報錯了呢。調試
繼續沿着這個思路,我去尋找了: 如何在csproj 文件中指定多個 targetframework ,因而也便有了這個提問,如何發佈多個 TargetFramework 的nuget 包 。當我設置完了這個目標框架,測試時發現,怎麼仍是不行呢。我發現我可能走錯路了,可能根本就不是這個地方出現問題了,是否是我問題定位的有問題。並且奇怪的是,code
爲何若是我本地目標框架是 .netcoreapp2.0 或者 .net standard2.0 時就不會報錯呢?好奇怪。orm
因而,我繼續開始設置斷點進行調試,最終發現了,每次走到下面這段代碼時就會曝出上面那條錯誤:
httpWebRequest.Headers.Add(header.Key, header.Value);
這究竟是爲何呢,爲何添加其餘屬性時就不會有這個錯,終於仍是在微軟的官方文檔上找到了答案:
HttpWebRequest exposes common HTTP header values sent to the Internet resource as properties, set by methods, or set by the system; the following table contains a complete list. You can set other headers in the Headers property as name/value pairs. Note that servers and caches may change or add headers during the request.
The following table lists the HTTP headers that are set either by properties or methods or the system.
Header Set by Accept Set by the Accept property. Connection Set by the Connection property, KeepAlive property. Content-Length Set by the ContentLength property. Content-Type Set by the ContentType property. Expect Set by the Expect property. Date Set by the system to current date. Host Set by the system to current host information. If-Modified-Since Set by the IfModifiedSince property. Range Set by the AddRange method. Referer Set by the Referer property. Transfer-Encoding Set by the TransferEncoding property (the SendChunked property must be true
).User-Agent Set by the UserAgent property.
也就是說呢,若是你的Headers中沒有包含上述的12個屬性,我就當成它爲保留屬性把,你均可以用如下命令設置
httpWebRequest.Headers.Add(header.Key, header.Value);
然而當涉及到上述的屬性的話,你就須要像下面這樣
if(header.key.contains("User-Agent")) { httpWebRequest.UserAgent = "Set as you like"; }
總結起來仍是經驗不夠,小問題定位錯誤致使排查錯了方向,一旦找對方向,就很容易解決啦。
PS:下一篇寫一下 httpWebrequest 中的timeout,這個也坑死我了。