尝试创建HttpContent时,在Http帖子中抛出InvalidOperationException

时间:2014-11-01 02:07:33

标签: c# http post

我已经制作了一个需要通过http将数据发布到网址的应用程序,下面是我发布数据的代码:

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'.流程

代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

哦,我想通了......

我改变了创建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();

    //I changed this line.
    System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(convertNameValueCollectionToKeyValuePair(HttpUtility.ParseQueryString(objPostData.ToString()));

    using(System.Net.Http.HttpResponseMessage response = client.PostAsync(strAddr, content).Result) {}
}