Get response data from SendAsync method ASP.net web API Message Handlers

1.3k views Asked by At

I want to fetch returned data from Web api and save in my database.

My Message handler code is here:

protected override async Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken)
{
    Stopwatch watch = new Stopwatch();
    TimeSpan second;
    watch.Start();
    // Call the inner handler.
    var response = await base.SendAsync(request, cancellationToken);
    watch.Stop();
    second = watch.Elapsed;
    watch.Reset();
    if (second.Seconds > 5)
    {
        try
        {
            var req = JsonConvert.SerializeObject(request.GetRouteData());
            var data = JsonConvert.SerializeObject(response.Content);

            var container = UnityConfig.GetConfiguredContainer();
            IPerformanceBal performance = container.Resolve<PerformanceBal>();
            performance.SavePerformance(new ApiPerformance()
            {
                CreatedAt = DateTime.Now,
                ExecutionTime = second,
                QueryResult = data,
                Uri = request.RequestUri.AbsoluteUri
            });
        }
        catch (Exception exception)
        {

        }
    }

    return response;
}

I want actually to get data in "data" variable returned from response... somethig like "response.data"... Any Help on thhis??

1

There are 1 answers

0
Nkosi On BEST ANSWER

You can access the response content directly using the HttpContent.ReadAsStringAsync Method method like this...

//...other code

var responseContent = await response.Content.ReadAsStringAsync();

//...other code

From there you should be able to use it as needed.