我如何从UploadStringTaskAsync调用中检索传递的数据

时间:2015-09-11 14:28:19

标签: c# asp.net asp.net-mvc-5 webclient

我有以下webclient: -

using (WebClient wc = new WebClient())
   {

 var url = currentURL+ "home/scanserver";
 wc.Headers.Add("Authorization", token);
 var json =wc.UploadStringTaskAsync(url, "FQDN=allscan");
   }

现在我正在通过安全令牌&名为FQDN的数据。所以在接收器上Post动作方法我无法检索FQDN参数,

我尝试了以下但没有工作

string FQDN = Request.Form["FQDN"];

我也尝试在action方法参数中定义FQDN,如下所示: - public async Task<ActionResult> ScanServer(string FQDN)

3 个答案:

答案 0 :(得分:1)

如果FQDN是query parameter,请尝试

using (WebClient wc = new WebClient())
{
  var url = currentURL+ "home/scanserver?FQDN=allscan";
  wc.Headers.Add("Authorization", token);
  var json =wc.UploadStringTaskAsync(url, "");
}

修改

要以表单形式发布,请使用UploadValuesTaskAsync方法。

var url = currentURL+ "home/scanserver";
var args = new NameValueCollection { { "FQDN", "allscan" } };
var json = wc.UploadValuesTaskAsync(url, args);

json现在是Task<byte>而不是Task<string>,因此您必须将其转换为string;

之类的东西
var s = Encoding.Utf8.GetString(json.Result);

答案 1 :(得分:1)

对于一个简单的查询参数,你可以像@Richard所说的那样做

using (WebClient wc = new WebClient())
{
    var url = currentURL+ "home/scanserver?FQDN=allscan";
    wc.Headers.Add("Authorization", token);
    var json =wc.UploadStringTaskAsync(url, "");
}

或者,如果您想发送长字符串或复杂对象MyObject,那么您可以这样做

using (WebClient wc = new WebClient())
{
    var url = currentURL+ "home/scanserver";
    wc.Headers.Add("Authorization", token);
    wc.Headers[HttpRequestHeader.ContentType] = "application/json";
    //here you can also pass a json serialized complex object
    var json =wc.UploadStringTaskAsync(url, "{FQDN:'allscan'}"); 
}

我在这里假设你的api方法看起来像

public void scanserver(string FQDN) //OR (MyClass myObject)
{
    //do something with token and FQDN 
    //OR use your complex object - myObject
}

答案 2 :(得分:0)

UploadStringTaskAsync的返回值为Task<string>。您需要等待返回的任务,添加延续,或阻止线程等待返回结果。

阻止方法:

using (WebClient wc = new WebClient())
{
    var url = currentURL+ "home/scanserver";
    wc.Headers.Add("Authorization", token);
    var json = wc.UploadStringTaskAsync(url, "FQDN=allscan").Result;
}

使用await(必须在标记为async的方法内):

string json;
using (WebClient wc = new WebClient())
{
    var url = currentURL + "home/scanserver";
    wc.Headers.Add("Authorization", token);
    json = await wc.UploadStringTaskAsync(url, "FQDN=allscan");
}