[英]How to return the result in async Task
我想將異步任務的值作為字符串返回,當我實現它時,會出現錯誤消息 System.NullReferenceException is unhandled 消息:mscorlib.dll 中發生了“System.NullReferenceException”類型的未處理異常附加信息:Z497031794414A552435F90151AC3B54ZB設置為 object 的實例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace USCInventoryService.CLASS
{
public static class RestFulHelper
{
private static readonly string baseURL = Properties.Settings.Default.Uri;
public static string BeautifyJson(string jsonStr)
{
JToken parseJson = JToken.Parse(jsonStr);
return parseJson.ToString(Formatting.Indented);
}
public static async Task<string> PostRFID(string token, string RFID, string status)
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
var inputData = new Dictionary<string, string>
{
{"token",token },
{"RFID",RFID },
{"status", status}
};
var input = new FormUrlEncodedContent(inputData);
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.PostAsync(baseURL + "transaction/api", input))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
}
}
Call in Service.asmx
[WebMethod]
public async Task<string> PostChkAccessPoint(string _token, string _RFID, string _status)
{
var response = await CLASS.RestFulHelper.PostRFID(_token, _RFID, _status);
string _res = CLASS.RestFulHelper.BeautifyJson(response);
return await Task.FromResult(_res);
}
為什么不試試這個
....
var formFields = new List<KeyValuePair<string,string>> {
new KeyValuePair<string,string>("token",token)),
new KeyValuePair<string,string>("RFID",RFID )),
new KeyValuePair<string,string>("status", status));
var formContent = new FormUrlEncodedContent(formFields);
using (HttpClient client = new HttpClient())
{
var response = await client.PostAsync(baseURL + "/transaction/api", formContent ))
if (response.IsSuccessStatusCode)
{
return await response.content.ReadAsStringAsync();
}
}
或者您可以嘗試:
var formFields = new Dictionary<string, string>(){
{"token",token },
{"RFID",RFID },
{"status", status}
};
var formContent = new StringContent(JsonConvert.SerializeObject(formFields), UnicodeEncoding.UTF8, "application/json");
和這個
[WebMethod]
public async Task<string> PostChkAccessPoint(string _token, string _RFID, string _status)
{
var responseString = await CLASS.RestFulHelper.PostRFID(_token, _RFID, _status);
return CLASS.RestFulHelper.BeautifyJson(responseString);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.