• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

355
Views
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;
        }
    }
}
about 3 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error