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

how i can retrive the passed data from UploadStringTaskAsync call

我有以下网络客户端:-

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"];

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

如果 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, "");
}

编辑

以post为形式使用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);

UploadStringTaskAsync 的 return 值为 Task<string>。您将需要等待 returned 任务,添加一个延续,或者阻塞线程以等待结果被 returned。

屏蔽方法:

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

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

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

对于一个简单的查询参数,你可以按照@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
}