I have two services, one REST api witch communicates with another service using grpc.
Trying to read the response metadata headers in the REST api with an grpc interceptor and set the values in the http response headers. It works fine for most of the request but sometimes it fails due to that the HttpContext is null. Probably because the http request already responded so the HttpContext no longer exists.
Can this be the case and can it be solved in another way?
public class SetHeaderInterceptor : Interceptor
{
private readonly IHttpContextAccessor _httpContext;
public SetHeaderInterceptor(IHttpContextAccessor httpContext)
{
_httpContext = httpContext;
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context,
AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
var call = continuation(request, context);
var response = new AsyncUnaryCall<TResponse>(call.ResponseAsync, HandleHeader<Metadata>(call.ResponseHeadersAsync), call.GetStatus, call.GetTrailers, call.Dispose);
return response;
}
private async Task<Metadata> HandleHeader<TResponse>(Task<Metadata> responseHeadersAsync)
{
try
{
var response = await responseHeadersAsync;
string header = response.GetValue("HeaderKey");
if (!string.IsNullOrEmpty(header))
{
if (_httpContext?.HttpContext?.Request != null)
{
_httpContext.HttpContext.Response.Headers.Add("HeaderKey", header);
}
}
return response;
}
catch (RpcException ex)
{
return default;
}
}
}