【问题标题】:How to return the result in async Task如何在异步任务中返回结果
【发布时间】:2021-07-31 23:03:58
【问题描述】:

我想将异步任务的值作为字符串返回,当我实现它时发生错误并显示错误消息 System.NullReferenceException is unhandled 消息:mscorlib.dll 中出现“System.NullReferenceException”类型的未处理异常 附加信息:对象引用未设置为对象的实例。

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);
    }

【问题讨论】:

  • 你已经正确地返回了结果,并且正确地等待它;我怀疑异常来自不是特定于字符串实际返回的东西;如果你在调试器中运行它,它会在哪里爆炸?
  • 这一行发生错误:using (HttpResponseMessage res = await client.PostAsync(baseURL + "transaction/api", input))
  • "这一行发生错误" - 很好;现在调试它; null 是什么部分?大概不是client,但是input呢?
  • 输入不为空

标签: c# asynchronous return task


【解决方案1】:

为什么不试试这个

....

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);
}
        

【讨论】:

  • 同样的错误,在 mscorlib.dll 中发生了“System.NullReferenceException”类型的未处理异常附加信息:对象引用未设置为对象的实例。
  • 您可以使用调试器并定义此错误发生的位置吗?
  • 这一行发生错误:var response = await client.PostAsync(baseURL + "/transaction/api", input);
  • 你检查baseurl值和输入值了吗?
  • 是的,baseurl 很好,没问题。当我作为 async void 执行时,我没有问题,但我想将结果作为字符串返回
猜你喜欢
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多