0

I have two applications running together at the same time. In my mvc project I have a middleware that will use TempData in order to pass the values of username and ipAddress and add it to the response headers. What I am trying to do is with those headers that are added in the middleware of the mvc project is to pass those headers over to the web api project so I can be able to use the username and ipaddress and have the same correlationid. How can I send/forward those custom headers that are in the mvc project over to the web api project?

Middleware in mvc project:

public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
    public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
        _tempDataDictionaryFactory = tempDataDictionaryFactory;
    }

    public async Task Invoke(HttpContext context)
    {
        string correlationId = null;
        string userName;
        string ipAddress;

        var tempData = _tempDataDictionaryFactory.GetTempData(context);

        var key = context.Request.Headers.Keys.FirstOrDefault(n => n.ToLower().Equals("x-correlation-id"));
        if (!string.IsNullOrWhiteSpace(key))
        {
            correlationId = context.Request.Headers[key];
            _logger.LogInformation("Header contained CorrelationId: {@CorrelationId}", correlationId);
        }
        else
        {
            if (tempData.ContainsKey("username") && tempData.ContainsKey("ipaddress"))
            {
                userName = tempData.Peek("username").ToString();
            
                ipAddress = tempData.Peek("ipaddress").ToString();

                context.Response.Headers.Append("X-username", userName);
                context.Response.Headers.Append("X-ipAddress", ipAddress);
            }

            correlationId = Guid.NewGuid().ToString();
            _logger.LogInformation("Generated new CorrelationId: {@CorrelationId}", correlationId);
        }
        context.Response.Headers.Append("x-correlation-id", correlationId);
        using (LogContext.PushProperty("CorrelationId", correlationId))
        {
            await _next.Invoke(context);
        }
    }
}

now moving to my web api project:

At first I had the same exact code for my mvc middleware but it never entered the if statement for the tempdata.containkey so I removed tempdata implementation.

public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        string correlationId = null;

        var key = context.Request.Headers.Keys.FirstOrDefault(n => n.ToLower().Equals("x-correlation-id"));
        if (!string.IsNullOrWhiteSpace(key))
        {
            correlationId = context.Request.Headers[key];
            _logger.LogInformation("Header contained CorrelationId: {@CorrelationId}", correlationId);
        }
        else
        {
            correlationId = Guid.NewGuid().ToString();
            _logger.LogInformation("Generated new CorrelationId: {@CorrelationId}", correlationId);
        }
        context.Response.Headers.Append("x-correlation-id", correlationId);
        using (LogContext.PushProperty("CorrelationId", correlationId))
        {
            await _next.Invoke(context);
        }
    }
}
2
  • You need to add the headers to the HttpClient before making the API call. You'll need the home controller to store the headers, or somehow pass the headers back to the home controller before invoking the HttpClient logic. Commented Aug 13, 2021 at 15:06
  • Thank you, will attempt either one and see how it goes! Commented Aug 13, 2021 at 16:13

1 Answer 1

1

Your HttpClient call works independently of your controllers and middleware.

You need to add the headers to the HttpClient before making the API call. To do this you'll need the home controller to store the headers, or somehow pass the headers back to the home controller, then pass them into the HttpClient logic

Sign up to request clarification or add additional context in comments.

8 Comments

When it comes to adding the headers in the homecontroller of the mvc to get the value/pass the headers to the web api project would you do it the way I did it in the updated section of the post?
depends on your use case. I personally try to avoid the complexity of the middleware. I may try to add this correlationid as a Claim if it made sense to do so.
Sorry I am not following, how would I go about doing this? I am new to this :(
Does your application have any authentication currently - Do users need to log in? This page describes it in the latest .net 5: learn.microsoft.com/en-us/aspnet/core/security/authentication/… but it is similar in older versions.
I see your update, that's basically the idea. Now you need to actually call the api with the HttpClient. client.GetAsync or client.PostAsync would make a Get or a Post call respectively.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.