2016-08-18 7 views
0

ASP.NET WebAPI 2.0を使用し、概念的な問題があります。WebAPI 2.0通話監視

すべてのユーザー/クライアントから呼び出されるAPIのグローバルレコードを保持したい場合、これがデータベースに格納されていれば素晴らしいと思います。

これを達成するための最良のメカニズムは何でしょうか?

答えて

2

私は'DelegatingHandlerを長年使っていますが、いくつかのプロジェクトでうまくやっています。このアプローチにより、

public class ApiCallLogHandler : DelegatingHandler { 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { 

     var started = DateTime.UtcNow; 
     HttpResponseMessage response = null; 
     Exception baseException = null; 

     try { 
      response = await base.SendAsync(request, cancellationToken); 
     } catch(Exception exception) { 
      CommonLogger.Logger.LogError(exception); 
      baseException = exception; 
     } 

     try { 
      var callModel = await GetCallModelAsync(request, response); 
      if(baseException != null) 
       callModel.Exception = baseException 
      callModel.ExecutionTime = (DateTime.UtcNow - started).ToString(); 
      await CommonLogger.Logger.LogApiCallAsync(callModel); 
     } catch (Exception exception) { 
      CommonLogger.Logger.LogError(exception); 
     } 

     return response; 
    } 

    private async Task<ApiCallModel> GetCallModelAsync(HttpRequestMessage request, HttpResponseMessage response) { 
     // parse request and response and create a model to store in database... 
    } 
} 

あなたはすべての要求、実行中の例外、および各API呼び出しのも、完全な応答を追跡することができます。

ApiCallModelは、要求と応答から必要なデータを入力する単純なPOCOクラスです。

CommonLogger.Logger.*は、あなたのロギングメカニズムです。

そして、あなたはこのスニペットでハンドラを登録する必要があります。これは素晴らしいです

public static class WebApiConfig { 
    public static void Register(HttpConfiguration config) { 
     config.MessageHandlers.Add(new ApiCallLogHandler()); 
    } 
} 
+0

おかげで、どのように私は、データベース内のデータを保存することができるだろうか? – user1144596

+0

@ user1144596)それは 'CommonLogget.Logger。*'または単にカスタムメソッドで行います。あなたはEFやNHやASO.NET、あるいはあなたが望む他のどのような仕組みを使うこともできます。より具体的にお願いしますか? –

+0

ああ、私はあなたが意味するものを参照してください。ありがとうございます – user1144596