Add support for advanced context in request/response interceptors in generated C# client
See original GitHub issueCurrent Behavior
Currently the request interception methods generated in C# clients are:
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
The Problem
The existing interception mechanism gives very little context about the API that is being called (basically just the URL), which blocks implementation of many useful or even critical interceptions.
For example - in one our Swagger-based API we store the OAuth scopes required on each endpoint in OpenAPI Flow objects. Hence, we need to extend the generated proxy to add the correct token to the correct endpoint. With the current approach, this is not possible (afaik).
Suggested solution
The generated interception methods should be passed a “context” object that should contain all information about the endpoint called that can be extracted from the OpenAPI specification. The signature of those methods could then look something like this:
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, OpenApiRequestContext context);
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response, OpenApiRequestContext context);
where
public class OpenApiRequestContext
{
public OpenApiContext Api { get; }
public OpenApiEndPointContext EndPoint { get; }
}
I also believe that the interception methods should use Async pattern because it might be necessary to perform an I/O operation to get the access token. Hence, this would be even better:
partial Task PrepareRequestAsync(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, OpenApiRequestContext context);
partial Task ProcessResponseAsync(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response, OpenApiRequestContext context);
Issue Analytics
- State:
- Created 6 years ago
- Reactions:12
- Comments:9 (5 by maintainers)
I’ve also just run into the issue of needing asynchronous logic within the PrepareRequest method, in my case I need to retrieve an access token via the OAuth client credentials flow. (Which is cached, but access tokens can expire so I can’t just retrieve it once)
Update: It would also be handy to have the cancellation token available in this extension point, if it were made asynchronous.
Partial methods got some nice upgrades in C# 9 - they can now return values, see: https://blog.miguelbernard.com/c-9-extending-partial-methods