Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global request/response interceptor

Tags:

servicestack

What would be the easiest way to setup a request/response interceptor in ServiceStack that would execute for a particular service?

A request filter (IHasRequestFilter) works fine but a response filter (IHasResponseFilter) is not triggered if the service returns non 2xx status code. I need to retrieve the status code returned by the method as well as the response DTO (if any).

A custom ServiceRunner and overriding the OnBeforeExecute and OnAfterExecute methods seems to work fine but I find it pretty intrusive as the service runner need to be replaced for the entire application and I couldn't find a way clean way to isolate per functionality the tasks that need to be executed in those methods.

Is there some extension point in ServiceStack that I am missing that would allow me to execute some code before each service method and after each service method? A plugin would be ideal but how can I subscribe to some fictitious BeforeExecute and AfterExecute methods that would allow me to run some custom code?


UPDATE:

Just after posting the question I found out that global response filters are executed no matter what status code is returned by the service which is exactly what I needed. So one last question: Is it possible to retrieve the service type that will handle the request in a request filter? I need to check whether this service is decorated by some custom marker attribute.

like image 359
Darin Dimitrov Avatar asked Jul 08 '13 12:07

Darin Dimitrov


People also ask

How do you intercept API response?

To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can: Get access to request headers and bodies and response headers.

What are request interceptors?

A request interceptor is a piece of code that gets activated for every single HTTP request received by your application. Interceptors are very useful when you need to perform some common processing for every HTTP request.

What is axios interceptors response?

Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.

What are interceptors in Javascript?

Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more.


1 Answers

I have found out a solution to my question about how to retrieve the service type in a custom request/response filter:

appHost.RequestFilters.Add((req, res, requestDto) =>
{
    var metadata = EndpointHost.Metadata;
    Type serviceType = metadata.GetServiceTypeByRequest(requestDto.GetType());

    ...
}
like image 200
Darin Dimitrov Avatar answered Sep 21 '22 16:09

Darin Dimitrov