首页 > 解决方案 > 如何从字符串方法中获取异步值

问题描述

我正在使用 API 形式的async方法和我的代码如下,

public async void Test(string token, int tenantId, string fromDate,string searchText)
 {
    try
    {
        string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

        string jsonParamterData = new JavaScriptSerializer().Serialize(new
        {
            FromDate = fromDate,
            SearchText = searchText,
        });

        HttpClient client = new HttpClient();

        HttpMethod method = new HttpMethod("POST");
        HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

        StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
        client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
        client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
        message.Content = content;

        var response = await client.PostAsync(serviceUrl, content);
        var result = await response.Content.ReadAsStringAsync();

        client.Dispose();
    }
  }

我需要从另一种方法获得响应结果。

public string GetValue(){

   
}

但是Test()方法是无效的,那么如何Test()从另一个方法访问结果值呢?是否可以在async方法中返回值。

更新:

[WebMethod(EnableSession = true)]
    public string GetValue(){
       
    }

但是 GetValue()是一种网络方法

标签: c#asynchronousasync-await

解决方案


你应该做这样的事情:

public async Task<string> Test(string token, int tenantId, string fromDate,string searchText)
{

    string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

    string jsonParamterData = new JavaScriptSerializer().Serialize(new
    {
        FromDate = fromDate,
        SearchText = searchText,
    });

    HttpClient client = new HttpClient();

    HttpMethod method = new HttpMethod("POST");
    HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

    StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
    client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
    client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
    message.Content = content;

    var response = await client.PostAsync(serviceUrl, content);
    var result = await response.Content.ReadAsStringAsync();

    client.Dispose();
    return result;
}

我强烈建议您避免使用 asmx 来执行异步函数,因为它已被弃用和停止使用。为了更清楚,我应该说 async/await 模式在较低版本的网络框架中有一些开销。您至少可以使用基于 dotnet-core 或 .NetFramework 最新版本(如 4.6+)的 Wcf 服务。另一种选择是使用带有基于 Aspnet 或 AspnetCore 的异步/等待承诺的 Rest API。但是,如果您选择继续当前的解决方案,您可以在此处查看 asmx WebMethods 的异步执行: https ://docs.microsoft.com/en-us/previous-versions/dotnet/articles/aa480516(v=msdn.10 )?redirectedfrom=MSDN

如果你想同时使用 AsyncCallBack 和 async/await 模式,你可以这样做:

public IAsyncResult BeginGetvalue(AsyncCallback cb, Object state)
{
    Action action = async () => {
       string result = await GetValue();
    };

    return action.BeginInvoke(cb, state);
}

我应该再次注意:请不要自己这样做。不推荐使用 ASMX 解决方案 :( 使用这些技术来处理您的解决方案:

  • 基于 netcore + kestrel 的异步 Restful api
  • 基于aspnet-mvc + self-hosted-owin的异步Restful api
  • 基于http2+和.net5的Grpc解决方案
  • 网络框架上的 netcore 中的 Wcf 服务。以上所有技术都支持异步方法。

推荐阅读