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

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'.
密码怎么了?

最佳答案

哦,我想出来了…
我改变了创建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) {}
}

关于c# - 尝试创建HttpContent时在Http帖子中引发InvalidOperationException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26685632/

10-11 11:44