I am working on an asp.net mvc-4 web application , and i have the following method to upload a json object to a 3rd part application. where i want to set the url header as application/x-www-form-urlencoded
:-
using (WebClient wc = new WebClient())
{
string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
Uri uri = new Uri(url);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var encodedJson = WebUtility.UrlEncode(data);
crudoutput = wc.UploadValues(uri, "INPUT_DATA=" + encodedJson);
}
but the above is raising the following error :-
cannot convert from 'string' to 'System.Collections.Specialized.NameValueCollection'
The best overloaded method match for 'System.Net.WebClient.UploadValues(System.Uri, System.Collections.Specialized.NameValueCollection)' has some invalid arguments
so can anyone adivce on this please ?
You need to define a new NameValueCollection
and pass it to UploadValues
:
crudoutput = wc.UploadValues(uri, new NameValueCollection()
{
{ "INPUT_DATA", encodedJson }
});
WebClient UploadValues
method is expecting an NameValueCollection
instead of string
as parameter
So you can try this :-
using (WebClient wc = new WebClient())
{
string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
Uri uri = new Uri(url);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var encodedJson = WebUtility.UrlEncode(data);
NameValueCollection myNameValueCollection = new NameValueCollection();
myNameValueCollection.Add("INPUT_DATA",encodedJson);
crudoutput = wc.UploadValues(uri, myNameValueCollection);
}
the error is pretty clear. UploadValues
takes a NameValueCollection
not a string https://msdn.microsoft.com/en-us/library/9w7b4fz7(v=vs.110).aspx
You code should be
var nvc = new NameValueCollection();
nvc.Add("INPUT_DATA", encodedJson);
crudoutput = wc.UploadValues(uri, nvc);
You might try UploadString
instead: https://msdn.microsoft.com/en-us/library/0645045y(v=vs.110).aspx
crudoutput = wc.UploadString(uri, "INPUT_DATA=" + encodedJson);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.