从SendAsync方法ASP.net Web API消息处理程序获取响应数据

时间:2017-01-02 12:39:10

标签: c# asp.net-web-api delegates message-handlers

我想从Web api获取返回的数据并保存在我的数据库中。

我的消息处理程序代码在这里:

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

我希望实际获取数据&#34;数据&#34;从响应返回的变量...像#34; response.data&#34; ... 对此有何帮助?

1 个答案:

答案 0 :(得分:1)

您可以使用HttpContent.ReadAsStringAsync方法直接访问响应内容,如下所示......

//...other code

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

//...other code

从那里你应该可以根据需要使用它。