如何将自定义 headers 从 mvc 项目发送到 Web api 项目?

How to send custom headers from mvc project to a web api project?

我同时有两个应用程序 运行。在我的 mvc 项目中,我有一个中间件,它将使用 TempData 来传递 usernameipAddress 的值并将其添加到响应 headers。我想要做的是将那些 headers 添加到 mvc 项目的中间件中,将这些 headers 传递给网络 api 项目,这样我就可以使用用户名和 ipaddress 并具有相同的 correlationid。我怎样才能 send/forward 那些在 mvc 项目中的自定义 headers 到 Web api 项目?

Middleware 在 mvc 项目中:

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);
        }
    }
}

现在转到我的网站 api 项目:

起初我的 mvc 中间件有完全相同的代码,但它从未输入 tempdata.containkey 的 if 语句,所以我删除了 tempdata 实现。

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);
        }
    }
}

您的 HttpClient 调用独立于您的控制器和中间件工作。

您需要在调用 API 之前将 headers 添加到 HttpClient。为此,您需要家庭控制器存储 headers,或者以某种方式将 headers 传递回家庭控制器,然后将它们传递给 HttpClient 逻辑