1
我做這將需要通過HTTP數據發佈到URL的應用程序,下面是我如何上傳數據的代碼:出現InvalidOperationException在HTTP POST時拋出嘗試創建HttpContent
using(System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) {
//Initialize a HttpClient
client.BaseAddress = new Uri(strURL);
client.Timeout = new TimeSpan(0, 0, 60);
client.DefaultRequestHeaders.Accept.Clear();
FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(convertNameValueCollectionToKeyValuePair(HttpUtility.ParseQueryString(objPostData.ToString())));
//This is where I got stuck
System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<FormUrlEncodedContent> (formUrlEncodedContent, new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter());
using(System.Net.Http.HttpResponseMessage response = client.PostAsync(strAddr, content).Result) {}
}
protected static IEnumerable<KeyValuePair<string, string>> convertNameValueCollectionToKeyValuePair(NameValueCollection input) {
var values = new List<KeyValuePair<string, string>>();
foreach(var key in input.AllKeys) {
values.Add(
new KeyValuePair<string, string> (key, input[key]));
}
return values.AsEnumerable();
}
代碼運行順利,直到它碰上了這樣一行:
System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<FormUrlEncodedContent>(formUrlEncodedContent, new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter());
例外The configured formatter 'System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter' cannot write an object of type 'FormUrlEncodedContent'.
流動
有什麼不好的代碼?