我有一个mvc项目,将在我的中间件中传递一个tempdata["username"]
。但是当在if(tempdata.ContainsKey("username")
中调试我的中间件时,我注意到它只进入if语句一次,并且再也没有进入它。我读了这篇文章,解释了如何使用TempData
和如何保持数据,以便能够使用它不止一次,但在我的情况下,它不起作用。为了实现这个目标,我是否缺少了什么?
在我的应用程序我有4页,在家庭控制器上,它会要求我输入一个用户名。当我这样做时,它将在中间件中传递tempdata并进入if语句。当继续到post方法,我在一个新的页面上,它将不持有任何值。在第三次请求时,tempdata被删除。我如何解决这个问题,使它可以传递到我的所有页面?
HomeController
:
public IActionResult Index()
{
// Gather IP
var userip = Request.HttpContext.Connection.RemoteIpAddress;
_logger.LogInformation("IP address of user logged in: {@IP-Address}", userip);
// Call AddressService API
var result = _addressServiceClient.SampleAsync().Result;
_logger.Log(LogLevel.Information, "Home Page...");
return View();
}
[HttpPost]
public IActionResult AddressValidate(IFormCollection form)
{
// if radio button was checked, perform the following var request.
// username
username = form["UserName"];
TempData["username"] = username;
TempData.Keep("username");
//HttpContext.Items["username"] = username;
string status = form["Status"];
_logger.LogInformation("Current user logged in: {@Username}", username);
switch (status)
{
case "1":
_logger.LogInformation("Address entered was valid!");
break;
case "2":
_logger.LogError("Address entered was invalid!");
ViewBag.Message = string.Format("You did not enter your address correctly! Please enter it again!");
return View("Index");
case "3":
_logger.LogError("Invalid Address");
throw new Exception("Invalid Address");
}
var request = new AddressRequest
{
StatusCode = Convert.ToInt32(status),
Address = "2018 Main St New York City, NY, 10001"
};
var result = _addressServiceClient.ValidateAddress(request).Result;
return RedirectToAction("SecIndex", "Second");
}
middleware
:
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;
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"))
{
userName = tempData["username"].ToString();
context.Response.Headers.Append("X-username", userName);
}
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);
}
}
}
当您总是希望为另一个请求保留该值时,可以使用Peek。当保留的值依赖于附加的逻辑时,使用Keep。
在您的情况下,您必须使用Peek。使用val= TempData. peek ("username");
代替var val= TempData["username"]当你调用val= TempData["username"],在底层,返回数据后它自动调用TempData.Remove("username")。