Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

442
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda