Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

431
Vistas
Read response metadata headers with grpc interceptor and add values to HttpContext

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;
        }
    }
}
over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda