2017-01-02 87 views
1

我想從Web API獲取返回的數據並保存在我的數據庫中。從SendAsync方法獲取響應數據ASP.net 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; 
} 

其實我是想在「數據」變量來獲取數據,從響應返回... somethig像「response.data」 ...... 上thhis任何幫助?

+0

您可以訪問響應內容'await response.Content.ReadAsStringAsync()' – Nkosi

+0

@Nkosi - 它適用於我。謝謝。 –

回答

1

您可以直接訪問使用這樣的方法HttpContent.ReadAsStringAsync方法響應內容...

//...other code 

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

//...other code 

從那裏,你應該能夠使用它作爲必要的。