-1

I'm consuming API form the async method and my code as follows,

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

I need to get that response result from another method.

public string GetValue(){

   
}

But Test() method is void, So how can I access Test() result value from another method? IS it possible to return value inside async methods.

Updated:

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

But GetValue() is a web method

thomsan
  • 433
  • 5
  • 19
  • 5
    Your `Test` method should return `Task` instead of void. `async void` should only be used for asynchronous event handlers. – David L Jan 12 '21 at 22:23
  • @DavidL Then how can I access that method, can u provide me some complete code to do that – thomsan Jan 12 '21 at 22:24
  • 2
    Dispose `IDisposable`s with `using` blocks, that includes both `client` and `response` – Charlieface Jan 12 '21 at 22:31
  • 2
    As DavidL already said, [avoid async void](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void). I am repeating it just for posting the link that explains why. – Theodor Zoulias Jan 12 '21 at 22:50
  • @TheodorZoulias So then how can i consume those method inside web method. or have any possibility to change my `Test()` method – thomsan Jan 12 '21 at 22:57
  • If you’re still using asmx, it’s time to upgrade your codebase. – David L Jan 12 '21 at 22:59
  • Check this out: [Calling Task-based methods from ASMX](https://stackoverflow.com/questions/24078621/calling-task-based-methods-from-asmx). It seems that ASMX and async/await are not a good match, but nevertheless combining them is doable. – Theodor Zoulias Jan 12 '21 at 23:54

1 Answers1

2

You should do something like this dude:

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

I highly recommend you to avoid using asmx for executing async functions, because it's deprecated and discontinued. To be more clarified I should say async/await pattern has some over-heads in lower versions of net framework. You can use at least Wcf services based on dotnet-core or latest versions of .NetFramework like 4.6+. Another option is using Rest Apis with async/await promises based on Aspnet or AspnetCore. But if you choose to continue your current solution you can see here to check asynchronous execution of asmx WebMethods: https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa480516(v=msdn.10)?redirectedfrom=MSDN

And if you want to use AsyncCallBack and async/await pattern together you can do something like this:

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

    return action.BeginInvoke(cb, state);
}

And again I should note: PLEASE DON'T DO THIS WITH YOURSELF. ASMX IS DEPRECATED SOLUTION :( Use these technologies to handle your solutions:

  • Async Restful apis based on netcore + kestrel
  • Async Restful apis based on aspnet-mvc + self-hosted-owin
  • Grpc solutions based on http2+ and .net5
  • Wcf-Services in netcore on netframework. All of the above technologies support async methods.
Amir
  • 1,214
  • 7
  • 10