我正在开发一个asp.net mvc-4 Web应用程序,我有以下方法将json对象上传到第三方应用程序。我想将网址标题设置为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);
}
但上述情况引发了以下错误: -
无法从'string'转换为 'System.Collections.Specialized.NameValueCollection'
最佳重载方法匹配 “System.Net.WebClient.UploadValues(的System.Uri, System.Collections.Specialized.NameValueCollection)'有一些无效 参数
所以有人可以这样做吗?
答案 0 :(得分:3)
您需要定义新的NameValueCollection
并将其传递给UploadValues
:
crudoutput = wc.UploadValues(uri, new NameValueCollection()
{
{ "INPUT_DATA", encodedJson }
});
答案 1 :(得分:3)
WebClient UploadValues
方法需要NameValueCollection
而不是string
作为参数
所以你可以试试这个: -
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);
}
答案 2 :(得分:2)
错误很清楚。 UploadValues
需要NameValueCollection
而不是字符串https://msdn.microsoft.com/en-us/library/9w7b4fz7(v=vs.110).aspx
你的代码应该是
var nvc = new NameValueCollection();
nvc.Add("INPUT_DATA", encodedJson);
crudoutput = wc.UploadValues(uri, nvc);
您可以尝试使用UploadString
:https://msdn.microsoft.com/en-us/library/0645045y(v=vs.110).aspx
crudoutput = wc.UploadString(uri, "INPUT_DATA=" + encodedJson);