使用 httpContext asp.net core mvc 将用户名传递到 headers
Pass username into headers using httpContext asp.net core mvc
我想在我的中间件中将一个变量传递给 headers。在我的控制器中,我使用 username
来保存在视图中输入的值。然后我在想如果我使用 TempData
我可以将 username
的值传递给我的中间件 class 并将它添加到 header。我注意到在它最终进入 if 语句 ( if (tempData.ContainsKey("username"))
) 并添加 header 之后。当我继续下一页时,它将 return 返回到中间件...它不会输入 if 语句并继续下一行 correlationId = Guid.NewGuid()
.ToString();`。这是在中间件中传递变量并将其添加到 header 的正确方法吗?
控制器:
[HttpPost]
public IActionResult AddressValidate(IFormCollection form)
{
// if radio button was checked, perform the following var request.
// username
string username = form["UserName"];
TempData["username"] = username;
TempData.Keep();
string status = form["Status"];
_logger.LogInformation("Current user logged in: {@Username}", username);
......
return RedirectToAction("SecondIndex", "Second")
}
Middleware
:
public class CorrelationIdMiddleware
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
private const string CorrelationIdHeaderKey = "X-Correlation-ID";
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public async Task Invoke(HttpContext httpContext)
{
string correlationId = null;
string userName;
var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);
if (httpContext.Request.Headers.TryGetValue(
CorrelationIdHeaderKey, out StringValues correlationIds))
{
correlationId = correlationIds.FirstOrDefault(k =>
k.Equals(CorrelationIdHeaderKey));
_logger.LogInformation("CorrelationId from Request Header: {@correlationId} ", correlationId);
}
else
{
if (tempData.ContainsKey("username"))
{
userName = tempData["username"].ToString();
httpContext.Request.Headers.Add("X-username", userName);
}
correlationId = Guid.NewGuid().ToString();
httpContext.Request.Headers.Add(CorrelationIdHeaderKey,
correlationId);
_logger.LogInformation("Generated CorrelationId: {@correlationId}", correlationId);
}
httpContext.Response.OnStarting(() =>
{
if (!httpContext.Response.Headers.
TryGetValue(CorrelationIdHeaderKey,
out correlationIds))
httpContext.Response.Headers.Add(
CorrelationIdHeaderKey, correlationId);
return Task.CompletedTask;
});
await _next.Invoke(httpContext);
}
}
Session 像这样吗?
你应该把你写的逻辑代码写到httpContext.Response.OnStarting的header中。它对我有用。
我想在我的中间件中将一个变量传递给 headers。在我的控制器中,我使用 username
来保存在视图中输入的值。然后我在想如果我使用 TempData
我可以将 username
的值传递给我的中间件 class 并将它添加到 header。我注意到在它最终进入 if 语句 ( if (tempData.ContainsKey("username"))
) 并添加 header 之后。当我继续下一页时,它将 return 返回到中间件...它不会输入 if 语句并继续下一行 correlationId = Guid.NewGuid()
.ToString();`。这是在中间件中传递变量并将其添加到 header 的正确方法吗?
控制器:
[HttpPost]
public IActionResult AddressValidate(IFormCollection form)
{
// if radio button was checked, perform the following var request.
// username
string username = form["UserName"];
TempData["username"] = username;
TempData.Keep();
string status = form["Status"];
_logger.LogInformation("Current user logged in: {@Username}", username);
......
return RedirectToAction("SecondIndex", "Second")
}
Middleware
:
public class CorrelationIdMiddleware
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
private const string CorrelationIdHeaderKey = "X-Correlation-ID";
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public async Task Invoke(HttpContext httpContext)
{
string correlationId = null;
string userName;
var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);
if (httpContext.Request.Headers.TryGetValue(
CorrelationIdHeaderKey, out StringValues correlationIds))
{
correlationId = correlationIds.FirstOrDefault(k =>
k.Equals(CorrelationIdHeaderKey));
_logger.LogInformation("CorrelationId from Request Header: {@correlationId} ", correlationId);
}
else
{
if (tempData.ContainsKey("username"))
{
userName = tempData["username"].ToString();
httpContext.Request.Headers.Add("X-username", userName);
}
correlationId = Guid.NewGuid().ToString();
httpContext.Request.Headers.Add(CorrelationIdHeaderKey,
correlationId);
_logger.LogInformation("Generated CorrelationId: {@correlationId}", correlationId);
}
httpContext.Response.OnStarting(() =>
{
if (!httpContext.Response.Headers.
TryGetValue(CorrelationIdHeaderKey,
out correlationIds))
httpContext.Response.Headers.Add(
CorrelationIdHeaderKey, correlationId);
return Task.CompletedTask;
});
await _next.Invoke(httpContext);
}
}
Session 像这样吗?
你应该把你写的逻辑代码写到httpContext.Response.OnStarting的header中。它对我有用。