Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionAttributeFilter vs. Delegatinghandler - advantages/disadvantages?

I want to log incoming json data from request and outgoing json in response.

After some search i noticed that both customized ActionAttributeFilter and DelegatingHandler can be used. Are they any advantages/disadvantages ?

like image 787
Henrik Avatar asked May 23 '14 09:05

Henrik


2 Answers

Advantages / Disadvantages depends on your need.

Delegating handler is much higher in hierarchy of Web API request processing than ActionAttributeFilter. If you implement Delegating Handler, you are creating a Message handler, while if you create Action filter, your are creating filter that run just before the action method in the pipeline.

Although a message handler runs earlier in the pipeline, it can be advantageous in dealing requests at the earliest available opportunity. The message handler runs for all action methods, or at least all the action methods of a route. This should be considered when selecting the message handler to solve a problem. Action Filters can be applied to individual action methods, all methods in an Controller, or all methods across all controllers by configuring the filter as a global filter.

like image 135
Guanxi Avatar answered Sep 19 '22 06:09

Guanxi


For your particular requirement, i.e. logging request and response, you should use a delegating handler.

The advantage of this is you can build a log object from the request AND the response at the same time. This is because the delegating handler runs around the request and response so will have access to both.

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
  var log = new Log { Url = request.RequestUri };     
  var response = await base.SendAsync(request, cancellationToken);
  log.ContentLength = response.ContentLength;
  this.LogAsync(log);
  return response;
}

With ActionFilter you can have methods that will execute before AND after the request but not throughout so you will need to think about correlating the logs somehow.

like image 42
BritishDeveloper Avatar answered Sep 18 '22 06:09

BritishDeveloper