-
Notifications
You must be signed in to change notification settings - Fork 0
Interception methods
In case your solution needs global possibility to work with Request
object directly before call
or inspect result of this call by accessing Response
object - there are two intercepting methods which can be overridden in your client implementation.
NOTE: To globally add authentication header see Authentication. To globally add some headers, see Headers pages.
Add (override) method InterceptRequestBeforeCall
of base AbstractRestClient
class to get access to request object right before API call.
public class ClientWithInterceptors : AbstractRestClient
{
public ClientWithInterceptors(HttpClient httpClient, RestServiceSettings settings, ILogger logger)
: base(httpClient, settings, logger)
{
}
protected override void InterceptRequestBeforeCall(HttpRequestMessage request)
{
// Inspect request about to be sent to API.
// Tamper with its properties, if really needed.
// NOTE: Do not replace entire request object!
request.Headers.Add("More", "Interceptors");
}
}
Right after API call, overriding base class AbstractRestClient
method InterceptResponseAfterCall
to get access to Response object and (if was formed in client) - exception to be thrown by client.
Method expect boolean response, where TRUE means to allow client to throw exception (if such exists). FALSE will make client swallow exception and continue normally - here you should handle exception in your own way.
public class ClientWithInterceptors : AbstractRestClient
{
public ClientWithInterceptors(HttpClient httpClient, RestServiceSettings settings, ILogger logger)
: base(httpClient, settings, logger)
{
}
protected override bool InterceptResponseAfterCall(HttpResponseMessage? response, Exception? exception)
{
if (exception != null)
{
// Exception was created, you can handle it here
return false; // Prevent Client to throw exception, if you handled it here.
}
// TRUE means to allow client to throw exception as it normally would.
return true;
}
}