c# - InvalidOperationException thrown in Http post when try to create HttpContent -
c# - InvalidOperationException thrown in Http post when try to create HttpContent -
i've made application need post info through http url, below code on how post data:
class="lang-c# prettyprint-override">using(system.net.http.httpclient client = new system.net.http.httpclient()) { //initialize 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 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])); } homecoming values.asenumerable(); } the code runs smoothly until ran line:
system.net.http.httpcontent content = new system.net.http.objectcontent<formurlencodedcontent>(formurlencodedcontent, new system.net.http.formatting.formurlencodedmediatypeformatter()); the exception the configured formatter 'system.net.http.formatting.formurlencodedmediatypeformatter' cannot write object of type 'formurlencodedcontent'. flows
what's wrong code?
oh figured out...
i changed method of creating httpcontent...
using(system.net.http.httpclient client = new system.net.http.httpclient()) { //initialize httpclient client.baseaddress = new uri(strurl); client.timeout = new timespan(0, 0, 60); client.defaultrequestheaders.accept.clear(); //i changed 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# http post
Comments
Post a Comment